Inheritance: System.Reflection.NonTypeMemberBase
Ejemplo n.º 1
1
        public static object deserializedField(FieldInfo prop, string value)
        {
            if (string.IsNullOrEmpty(value))
                return null;

            Type proptype = prop.FieldType;

            if (proptype.IsGenericType && proptype.GetGenericTypeDefinition() == typeof(List<>))
            {
                object objfield = proptype.GetConstructor(Type.EmptyTypes).Invoke(null);
                Type listParamType = proptype.GetGenericArguments()[0];

                String[] arrays = value.Split(ListSeparation);

                for (int i = 0; i < arrays.Length; ++i)
                {
                    object arr_element = Data.Converter.GetValue(listParamType, arrays[i]);
                    proptype.GetMethod("Add").Invoke(objfield, new object[] { arr_element });
                }
                return objfield;
            }
            else
            {
                return Data.Converter.GetValue(proptype, value);
            }
        }
Ejemplo n.º 2
1
 public override void ApplyToFieldInfo(FieldInfo Info, ISerializablePacket Packet, Type Field)
 {
     if (Field.Equals(typeof(bool)))
         Info.SetValue(Packet, val);
     else
         Info.SetValue(Packet, Convert.ChangeType((bool)val, Info.FieldType));
 }
Ejemplo n.º 3
1
        /// <summary>
        /// 判断字段的过虑条件。
        /// </summary>
        /// <param name="field"></param>
        /// <returns></returns>
        public static bool ProccessField(FieldInfo field)
        {
            if(field.FieldType.IsSubclassOf(typeof(Delegate)))
                return  false;

            return true;
        }
Ejemplo n.º 4
1
 public FieldGetter(FieldInfo fieldInfo)
 {
     _fieldInfo = fieldInfo;
     Name = fieldInfo.Name;
     MemberType = fieldInfo.FieldType;
     _lateBoundFieldGet = LazyFactory.Create(() => DelegateFactory.CreateGet(fieldInfo));
 }
        static DynamicScopeTokenResolver()
        {
            BindingFlags s_bfInternal = BindingFlags.NonPublic | BindingFlags.Instance;
            s_indexer = Type.GetType("System.Reflection.Emit.DynamicScope").GetProperty("Item", s_bfInternal);
            s_scopeFi = Type.GetType("System.Reflection.Emit.DynamicILGenerator").GetField("m_scope", s_bfInternal);

            s_varArgMethodType = Type.GetType("System.Reflection.Emit.VarArgMethod");
            s_varargFi1 = s_varArgMethodType.GetField("m_method", s_bfInternal);
            s_varargFi2 = s_varArgMethodType.GetField("m_signature", s_bfInternal);

            s_genMethodInfoType = Type.GetType("System.Reflection.Emit.GenericMethodInfo");
            s_genmethFi1 = s_genMethodInfoType.GetField("m_methodHandle", s_bfInternal);
            s_genmethFi2 = s_genMethodInfoType.GetField("m_context", s_bfInternal);

            s_genFieldInfoType = Type.GetType("System.Reflection.Emit.GenericFieldInfo", false);
            if (s_genFieldInfoType != null)
            {
                s_genfieldFi1 = s_genFieldInfoType.GetField("m_fieldHandle", s_bfInternal);
                s_genfieldFi2 = s_genFieldInfoType.GetField("m_context", s_bfInternal);
            }
            else
            {
                s_genfieldFi1 = s_genfieldFi2 = null;
            }
        }
 // public constructor to form the custom attribute with constructor and constructor
 // parameters.
 public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs,
                               PropertyInfo[] namedProperties, Object[] propertyValues,
                               FieldInfo[] namedFields, Object[] fieldValues)
 {
     InitCustomAttributeBuilder(con, constructorArgs, namedProperties,
                                propertyValues, namedFields, fieldValues);
 }
Ejemplo n.º 7
1
 public virtual void SetUp ()
 {
   _associatedExpression = ExpressionHelper.CreateExpression();
   _method = typeof (AnonymousType).GetMethod ("get_a");
   _property = typeof (AnonymousType).GetProperty ("a");
   _field = typeof (MemberBindingTestBase).GetField ("_associatedExpression", BindingFlags.Instance | BindingFlags.NonPublic);
 }
Ejemplo n.º 8
1
 private void AddModel(Type fragmentClass, FieldInfo field, InjectionAttribute injectionAttribute)
 {
     //  bool optional = field.HasAttribute<OptionalAttribute>() || injectionAttribute.IsOptional();
     //  var dependencyModel = new DependencyModel(injectionAttribute, field.FieldType, fragmentClass, optional);
     var injectedFieldModel = new InjectedFieldModel(field, injectionAttribute);
     this.fields.Add(injectedFieldModel);
 }
Ejemplo n.º 9
1
        /// <summary>
        /// Find the UIPartActionWindow for a part. Usually this is useful just to mark it as dirty.
        /// </summary>
        public static UIPartActionWindow FindActionWindow(this Part part)
        {
            if (part == null)
                return null;

            // We need to do quite a bit of piss-farting about with reflection to 
            // dig the thing out. We could just use Object.Find, but that requires hitting a heap more objects.
            UIPartActionController controller = UIPartActionController.Instance;
            if (controller == null)
                return null;

            if (windowListField == null)
            {
                Type cntrType = typeof(UIPartActionController);
                foreach (FieldInfo info in cntrType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic))
                {
                    if (info.FieldType == typeof(List<UIPartActionWindow>))
                    {
                        windowListField = info;
                        goto foundField;
                    }
                }
                Debug.LogWarning("*PartUtils* Unable to find UIPartActionWindow list");
                return null;
            }
            foundField:

            List<UIPartActionWindow> uiPartActionWindows = (List<UIPartActionWindow>)windowListField.GetValue(controller);
            if (uiPartActionWindows == null)
                return null;

            return uiPartActionWindows.FirstOrDefault(window => window != null && window.part == part);
        }
Ejemplo n.º 10
1
        internal static Expression CreateSetFieldExpression(Expression clone, Expression value, FieldInfo fieldInfo) {
            // workaround for readonly fields: use reflection, this is a lot slower but the only way except using il directly
            if (fieldInfo.IsInitOnly)
                return Expression.Call(Expression.Constant(fieldInfo), _fieldInfoSetValueMethod, clone, Expression.Convert(value, TypeHelper.ObjectType));

            return Expression.Assign(Expression.Field(clone, fieldInfo), value);
        }
Ejemplo n.º 11
1
 public FieldGetter(FieldInfo fieldInfo)
 {
     _fieldInfo = fieldInfo;
     _name = fieldInfo.Name;
     _memberType = fieldInfo.FieldType;
     _lateBoundFieldGet = DelegateFactory.CreateGet(fieldInfo);
 }
 private static MemberInfo[] GetSerializableMembers2(Type type)
 {
     // get the list of all fields
     FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
     int countProper = 0;
     for (int i = 0; i < fields.Length; i++)
     {
         if ((fields[i].Attributes & FieldAttributes.NotSerialized) == FieldAttributes.NotSerialized)
             continue;
         countProper++;
     }
     if (countProper != fields.Length)
     {
         FieldInfo[] properFields = new FieldInfo[countProper];
         countProper = 0;
         for (int i = 0; i < fields.Length; i++)
         {
             if ((fields[i].Attributes & FieldAttributes.NotSerialized) == FieldAttributes.NotSerialized)
                 continue;
             properFields[countProper] = fields[i];
             countProper++;
         }
         return properFields;
     }
     else
         return fields;
 }
Ejemplo n.º 13
1
        internal static GenericGetter CreateGetField(Type type, FieldInfo fieldInfo)
        {
            DynamicMethod dynamicGet = new DynamicMethod("_", typeof(object), new Type[] { typeof(object) }, type);

            ILGenerator il = dynamicGet.GetILGenerator();

            if (!type.IsClass) // structs
            {
                var lv = il.DeclareLocal(type);
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Unbox_Any, type);
                il.Emit(OpCodes.Stloc_0);
                il.Emit(OpCodes.Ldloca_S, lv);
                il.Emit(OpCodes.Ldfld, fieldInfo);
                if (fieldInfo.FieldType.IsValueType)
                    il.Emit(OpCodes.Box, fieldInfo.FieldType);
            }
            else
            {
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldfld, fieldInfo);
                if (fieldInfo.FieldType.IsValueType)
                    il.Emit(OpCodes.Box, fieldInfo.FieldType);
            }

            il.Emit(OpCodes.Ret);

            return (GenericGetter)dynamicGet.CreateDelegate(typeof(GenericGetter));
        }
 public static string CreateMessage(FieldInfo field)
 {
     return String.Format("Instance could not be created for field '{0}' of type '{1}' in Assembly '{2}'",
                             field.Name,
                             field.DeclaringType.FullName,
                             field.Module);
 }
Ejemplo n.º 15
1
 public FieldDecorator(Type forType, FieldInfo field, IProtoSerializer tail) : base(tail)
 {
     Helpers.DebugAssert(forType != null);
     Helpers.DebugAssert(field != null);
     this.forType = forType;
     this.field = field;
 }
Ejemplo n.º 16
1
Archivo: DecrPtr.cs Proyecto: paf31/BF
 public void EmitIL(ILGenerator body, FieldInfo tape, FieldInfo ptr)
 {
     body.Emit(OpCodes.Ldsfld, ptr);
     body.Emit(OpCodes.Ldc_I4_1);
     body.Emit(OpCodes.Sub);
     body.Emit(OpCodes.Stsfld, ptr);
 }
Ejemplo n.º 17
1
 /// <summary>
 /// Constructor
 /// </summary>
 public VariableField(object model, FieldInfo fieldInfo)
 {
     if (model == null || fieldInfo == null)
         throw new Exception("Cannot create an instance of class VariableField with a null model or fieldInfo");
     Object = model;
     FieldInfo = fieldInfo;
 }
		/// <summary>
		/// Dispatches the call to the extensions.
		/// </summary>
		/// <param name="fi">The field info reflection object.</param>
		/// <param name="model">The model.</param>
		public void ProcessField(FieldInfo fi, ActiveRecordModel model)
		{
			foreach(IModelBuilderExtension extension in extensions)
			{
				extension.ProcessField(fi, model);
			}
		}
	private void GenerateEnumMemberAttributes(FieldInfo fieldInfo)
	{	
		EnumMemberAttribute enumMemberAttr = (EnumMemberAttribute)Attribute.GetCustomAttribute(fieldInfo, typeof(EnumMemberAttribute));
        if (enumMemberAttr != null)
        {

this.Write("[System.Runtime.Serialization.EnumMember");


            string value = enumMemberAttr.Value;
            if (!string.IsNullOrEmpty(value))
            {

this.Write("(Value=");

this.Write(this.ToStringHelper.ToStringWithCulture(value.ToString()));

this.Write(")\r\n");


            }
this.Write("]");


		}
		
		this.GenerateAttributes(fieldInfo.GetCustomAttributes(false).Cast<Attribute>().Where(a => a.GetType() != typeof(EnumMemberAttribute)));
	}
Ejemplo n.º 20
1
        public void Visit(string settingsNamesapce, string fieldPath, FieldInfo rawSettingsField, object rawSettings)
        {
            // Skip 'sealed' fields.
            if (rawSettingsField.IsDefined<SealedAttribute>()) return;

            if (rawSettingsField.FieldType == typeof(string))
            {
                var originalString = (string)rawSettingsField.GetValue(rawSettings);
                if (originalString != null)
                {
                    var expandedString = ExpandVariables(originalString, _variables);
                    rawSettingsField.SetValue(rawSettings, expandedString);
                }
            }
            else if (rawSettingsField.FieldType == typeof(string[]))
            {
                string[] arr = (string[])rawSettingsField.GetValue(rawSettings);
                for (int i = 0; i < arr.Length; i++)
                {
                    string originalString = arr[i];
                    if (originalString != null)
                    {
                        var expandedString = ExpandVariables(originalString, _variables);
                        arr[i] = expandedString;
                    }
                }
            }
        }
        public virtual object Decorate(FieldInfo field)
        {
            if (!(typeof(IWebElement).IsAssignableFrom(field.FieldType)
                  || IsDecoratableList(field)))
            {
                return null;
            }

            IElementLocator locator = factory.CreateLocator(field);
            if (locator == null)
            {
                return null;
            }

            if (typeof(IWebElement).IsAssignableFrom(field.FieldType))
            {
                return ProxyForLocator(locator);
            }
            else if (typeof(IList).IsAssignableFrom(field.FieldType))
            {
                return ProxyForListLocator(locator);
            }
            else
            {
                return null;
            }
        }
Ejemplo n.º 22
1
 public RubyFieldInfo(FieldInfo/*!*/ fieldInfo, RubyMemberFlags flags, RubyModule/*!*/ declaringModule, bool isSetter, bool isDetached)
     : base(flags, declaringModule) {
     Assert.NotNull(fieldInfo, declaringModule);
     _fieldInfo = fieldInfo;
     _isSetter = isSetter;
     _isDetached = isDetached;
 }
Ejemplo n.º 23
1
        private List<string> _list; //Store the list of existing languages

        //[TestMethod]
        //public void TestAllLanguageTranslationsExists()
        //{
        //    Language defaultlang = new Language(); //Load the English version
        //    defaultlang.General.TranslatedBy = "Translated by ..."; // to avoid assertion

        //    foreach (String cultureName in _list) //Loop over all language files
        //    {
        //        //Load language
        //        var reader = new System.IO.StreamReader(Path.Combine(Configuration.BaseDirectory, "Languages") + Path.DirectorySeparatorChar + cultureName + ".xml");
        //        Language lang = Language.Load(reader);

        //        //Loop over all field in language
        //        checkFields(cultureName, defaultlang, lang, defaultlang.GetType().GetFields());

        //        checkProperty(cultureName, defaultlang, lang, defaultlang.GetType().GetProperties());

        //        //If u want to save a kind of fixed lang file
        //        //Disabled the assert fail function for it!
        //      //  lang.Save("Languagesnew\\" + cultureName + ".xml");
        //        reader.Close();
        //    }
        //}

        private void checkFields(string cultureName, object completeLang, object cultureLang, FieldInfo[] fields)
        {
            foreach (FieldInfo fieldInfo in fields)
            {
                if (fieldInfo.IsPublic && fieldInfo.FieldType.Namespace.Equals("Nikse.SubtitleEdit.Logic")) {
                    object completeLangatt = fieldInfo.GetValue(completeLang);
                    object cultureLangatt = fieldInfo.GetValue(cultureLang);

                    if ((cultureLangatt == null) || (completeLangatt == null))
                    {
                        Assert.Fail(fieldInfo.Name + " is mssing");
                    }
                    //Console.Out.WriteLine("Field: " + fieldInfo.Name + " checked of type:" + fieldInfo.FieldType.FullName);
                    if (!fieldInfo.FieldType.FullName.Equals("System.String"))
                    {
                        checkFields(cultureName, completeLang, cultureLang, fieldInfo.FieldType.GetFields());
                        checkProperty(cultureName, completeLangatt, cultureLangatt, fieldInfo.FieldType.GetProperties());
                    }
                    else
                    {
                        Assert.Fail("no expecting a string here");
                    }
                }
            }
        }
Ejemplo n.º 24
1
 private static IGetterAndSetter Create(FieldInfo fieldInfo)
 {
     var setter = typeof(GetterAndSetter<,>).MakeGenericType(fieldInfo.DeclaringType, fieldInfo.FieldType);
     var constructorInfo = setter.GetConstructor(new[] { typeof(FieldInfo) });
     //// ReSharper disable once PossibleNullReferenceException nope, not here
     return (IGetterAndSetter)constructorInfo.Invoke(new object[] { fieldInfo });
 }
Ejemplo n.º 25
1
		public void CreateProxiedMethod(FieldInfo field, MethodInfo method, TypeBuilder typeBuilder)
		{
			const MethodAttributes methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig |
																								MethodAttributes.Virtual;
			ParameterInfo[] parameters = method.GetParameters();

			MethodBuilder methodBuilder = typeBuilder.DefineMethod(method.Name, methodAttributes,
			                                                       CallingConventions.HasThis, method.ReturnType,
			                                                       parameters.Select(param => param.ParameterType).ToArray());

			System.Type[] typeArgs = method.GetGenericArguments();

			if (typeArgs.Length > 0)
			{
				var typeNames = new List<string>();

				for (int index = 0; index < typeArgs.Length; index++)
				{
					typeNames.Add(string.Format("T{0}", index));
				}

				methodBuilder.DefineGenericParameters(typeNames.ToArray());
			}

			ILGenerator IL = methodBuilder.GetILGenerator();

			Debug.Assert(MethodBodyEmitter != null);
			MethodBodyEmitter.EmitMethodBody(IL, method, field);
		}
		/// <summary>
		/// Creates a <see cref="ValueAccess"/> suitable for accessing the value in <paramref name="fieldInfo"/>.
		/// </summary>
		/// <param name="fieldInfo">The <see cref="FieldInfo"/></param> representing the field for which a
		/// <see cref="ValueAccess"/> is required.
		/// <returns>The <see cref="ValueAccess"/> that allows for accessing the value in <paramref name="fieldInfo"/>.</returns>
		/// <exception cref="ArgumentNullException">when <paramref name="fieldInfo"/> is <see langword="null"/>.</exception>
		public ValueAccess GetFieldValueAccess(FieldInfo fieldInfo)
		{
			if (null == fieldInfo)
				throw new ArgumentNullException("fieldInfo");

			return DoGetFieldValueAccess(fieldInfo);
		}
Ejemplo n.º 27
1
 public GlideInfo(object target, FieldInfo info)
 {
     Target = target;
     field = info;
     PropertyName = info.Name;
     PropertyType = info.FieldType;
 }
Ejemplo n.º 28
1
        public static IntList GetLines(RawText rawText)
        {
            if (_linesField == null)
                _linesField = typeof(RawText).GetField("lines", BindingFlags.NonPublic | BindingFlags.Instance);

            return (IntList)_linesField.GetValue(rawText);
        }
Ejemplo n.º 29
0
        public static byte[] GetContent(RawText rawText)
        {
            if (_contentField == null)
                _contentField = typeof(RawText).GetField("content", BindingFlags.NonPublic | BindingFlags.Instance);

            return (byte[])_contentField.GetValue(rawText);
        }
        public void Check(FieldInfo info, Dependency parent)
        {
            //            Dependency parent = new Dependency(info.);
            bool isInterface = info.FieldType.IsInterface;
            bool isAbstract = info.FieldType.IsAbstract;
            bool isNotSealed = !info.FieldType.IsSealed;

            string message = "";
            if (isInterface)
            {
                message = string.Format("Field {0} is interface {1}", info.Name, info.FieldType.Name);
            }
            else if (isAbstract)
            {
                message = string.Format("Field {0} is an abstract class {1} and can be inherited from", info.Name,info.FieldType.Name);

            }
            else if (isNotSealed)
            {
                message =
                    string.Format("Field {0} is non sealed {1} and can be inherited from", info.Name,
                                  info.FieldType.Name);
            }

            parent.Add(new Dependency(message));
            //            if (parent.AlreadyContains(info.FieldType))
            //            {
            //                parent.Add(new Dependency(message));
            //            }
            //            else
            //            {
            //                parent.Add(new Dependency(info.FieldType, message));
            //            }
        }
Ejemplo n.º 31
0
        public static string GetDescription(this Enum value)
        {
            Reflection.FieldInfo fieldInfo = value
                                             .GetType()
                                             .GetField(value.GetName());
            DescriptionAttribute descriptionAttribute = fieldInfo
                                                        .GetCustomAttributes(typeof(DescriptionAttribute)
                                                                             , false)
                                                        .FirstOrDefault()
                                                        as DescriptionAttribute;

            return(descriptionAttribute == null?value.GetName()
                       : descriptionAttribute.Description);
        }
Ejemplo n.º 32
0
 private static System.Type GetType(SerializedProperty property)
 {
     System.Type parentType         = property.serializedObject.targetObject.GetType();
     System.Reflection.FieldInfo fi = parentType.GetField(property.propertyPath);
     return(fi.FieldType);
 }
Ejemplo n.º 33
0
        protected override Expression VisitMemberAccess(MemberExpression m)
        {
            //TODO when member is declared by interface, this would solve, but need to find out implementors of interface to get backing field of property
            //if (m.Expression != null && (m.Expression.NodeType == ExpressionType.Convert || m.Expression.NodeType == ExpressionType.ConvertChecked))
            //{
            //    MemberExpression memExpr= Expression.MakeMemberAccess(((UnaryExpression)m.Expression).Operand ,m.Member) ;
            //   return this.VisitMemberAccess(memExpr);

            //}

            if (m.Expression != null && (m.Expression.NodeType == ExpressionType.Parameter || m.Expression.NodeType == ExpressionType.MemberAccess))
            {
                if (currentWhere == null)
                {
                    if (m.Type == typeof(bool)) //ex: WHERE Active
                    {
                        BinaryExpression exp = BinaryExpression.MakeBinary(ExpressionType.Equal, m, Expression.Constant(true));
                        return(this.VisitBinary(exp));
                    }
                }
#if WinRT
                if (m.Member.GetMemberType() == MemberTypes.Property)
#else
                if (m.Member.MemberType == System.Reflection.MemberTypes.Property)
#endif
                {
                    if (m.Member.Name == "OID")
                    {
                        currentWhere.AttributeName.Add("OID");
                        currentWhere.ParentType.Add(m.Member.DeclaringType);
                    }
                    else
                    {
                        if (m.Member.DeclaringType == typeof(string))
                        {
                            throw new Exceptions.LINQUnoptimizeException(string.Format("The member '{0}' is not supported", m.Member.Name));
                        }
                        System.Reflection.PropertyInfo pi = m.Member as System.Reflection.PropertyInfo;
                                                #if SILVERLIGHT || CF || UNITY3D || WinRT || MONODROID
                        string fieldName = SilverlightPropertyResolver.GetPrivateFieldName(pi, pi.DeclaringType);
                        if (fieldName != null)
                        {
                            currentWhere.AttributeName.Add(fieldName);
                            currentWhere.ParentType.Add(m.Member.DeclaringType);
                        }
                        else
                        {
                            string fld = Sqo.Utilities.MetaHelper.GetBackingFieldByAttribute(m.Member);
                            if (fld != null)
                            {
                                currentWhere.AttributeName.Add(fld);

                                currentWhere.ParentType.Add(m.Member.DeclaringType);
                            }
                            else
                            {
                                throw new SiaqodbException("A Property must have UseVariable Attribute set( property:" + m.Member.Name + " of type:" + m.Member.DeclaringType.ToString() + ")");
                            }
                        }
#else
                        try
                        {
                            System.Reflection.FieldInfo fi = BackingFieldResolver.GetBackingField(pi);
                            if (fi != null)
                            {
                                currentWhere.AttributeName.Add(fi.Name);

                                currentWhere.ParentType.Add(m.Member.DeclaringType);
                            }
                        }
                        catch
                        {
                            string fld = Sqo.Utilities.MetaHelper.GetBackingFieldByAttribute(m.Member);
                            if (fld != null)
                            {
                                currentWhere.AttributeName.Add(fld);

                                currentWhere.ParentType.Add(m.Member.DeclaringType);
                            }
                            else
                            {
                                throw new SiaqodbException("A Property must have UseVariable Attribute set( property:" + m.Member.Name + " of type:" + m.Member.DeclaringType.ToString() + ")");
                            }
                        }
#endif
                    }
                }
#if WinRT
                else if (m.Member.GetMemberType() == MemberTypes.Field)
#else
                else if (m.Member.MemberType == System.Reflection.MemberTypes.Field)
#endif
                {
                    currentWhere.AttributeName.Add(m.Member.Name);
                    currentWhere.ParentType.Add(m.Member.DeclaringType);
                }
                else
                {
                    throw new NotSupportedException("Unsupported Member Type!");
                }

                if (m.Expression.NodeType == ExpressionType.MemberAccess)
                {
                    return(base.VisitMemberAccess(m));
                }
                else
                {
                    return(m);
                }
            }

            throw new  Exceptions.LINQUnoptimizeException(string.Format("The member '{0}' is not supported", m.Member.Name));
        }
Ejemplo n.º 34
0
 private static System.Type GetType(SerializedProperty property)
 {
     System.Type parentType         = property.serializedObject.targetObject.GetType();
     System.Reflection.FieldInfo fi = NodeEditorWindow.GetFieldInfo(parentType, property.name);
     return(fi.FieldType);
 }
Ejemplo n.º 35
0
 static SR.FieldInfo ResolveFieldDefinition(SR.FieldInfo field)
 {
     return(field.Module.ResolveField(field.MetadataToken));
 }
Ejemplo n.º 36
0
 public static void Register()
 {
     global::Orleans.Serialization.SerializationManager.Register(typeof(Example.CreateInventoryItem), DeepCopier, Serializer, Deserializer);
     fieldInfo1 = typeof(Example.CreateInventoryItem).GetField("Name", (System.Reflection.BindingFlags.Instance
                                                                        | (System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic)));
 }
        public FieldReference Import(SR.FieldInfo field)
        {
            CheckField(field);

            return(MetadataImporter.ImportField(field, null));
        }
Ejemplo n.º 38
0
        // parses the alternate names
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("unchecked") private static <R extends Named> com.google.common.collect.ImmutableList<NamedLookup<R>> parseProviders(com.opengamma.strata.collect.io.IniFile config, Class<R> enumType)
        private static ImmutableList <NamedLookup <R> > parseProviders <R>(IniFile config, Type <R> enumType) where R : Named
        {
            if (!config.contains(PROVIDERS_SECTION))
            {
                return(ImmutableList.of());
            }
            PropertySet section = config.section(PROVIDERS_SECTION);

            ImmutableList.Builder <NamedLookup <R> > builder = ImmutableList.builder();
            foreach (string key in section.keys())
            {
                Type cls;
                try
                {
                    cls = RenameHandler.INSTANCE.lookupType(key);
                }
                catch (Exception ex)
                {
                    throw new System.ArgumentException("Unable to find enum provider class: " + key, ex);
                }
                string value = section.value(key);
                if (value.Equals("constants"))
                {
                    // extract public static final constants
                    builder.add(parseConstants(enumType, cls));
                }
                else if (value.Equals("lookup"))
                {
                    // class is a named lookup
                    if (!cls.IsAssignableFrom(typeof(NamedLookup)))
                    {
//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
                        throw new System.ArgumentException("Enum provider class must implement NamedLookup " + cls.FullName);
                    }
                    try
                    {
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: Constructor<?> cons = cls.getDeclaredConstructor();
                        System.Reflection.ConstructorInfo <object> cons = cls.DeclaredConstructor;
                        if (!Modifier.isPublic(cls.Modifiers))
                        {
                            cons.Accessible = true;
                        }
                        builder.add((NamedLookup <R>)cons.newInstance());
                    }
                    catch (Exception ex)
                    {
//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
                        throw new System.ArgumentException("Invalid enum provider constructor: new " + cls.FullName + "()", ex);
                    }
                }
                else if (value.Equals("instance"))
                {
                    // class has a named lookup INSTANCE static field
                    try
                    {
                        System.Reflection.FieldInfo field = cls.getDeclaredField("INSTANCE");
                        if (!Modifier.isStatic(field.Modifiers) || !field.Type.IsAssignableFrom(typeof(NamedLookup)))
                        {
//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
                            throw new System.ArgumentException("Invalid enum provider instance: " + cls.FullName + ".INSTANCE");
                        }
                        if (!Modifier.isPublic(cls.Modifiers) || !Modifier.isPublic(field.Modifiers))
                        {
                            field.Accessible = true;
                        }
                        builder.add((NamedLookup <R>)field.get(null));
                    }
                    catch (Exception ex)
                    {
//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
                        throw new System.ArgumentException("Invalid enum provider instance: " + cls.FullName + ".INSTANCE", ex);
                    }
                }
                else
                {
                    throw new System.ArgumentException("Provider value must be either 'constants' or 'lookup'");
                }
            }
            return(builder.build());
        }
Ejemplo n.º 39
0
 public FieldReference Import(SR.FieldInfo field, IGenericParameterProvider context)
 {
     return(ImportReference(field, context));
 }
 public FieldReference Import(SR.FieldInfo field, MethodReference context)
 {
     return(Import(field, (IGenericParameterProvider)context));
 }
Ejemplo n.º 41
0
 public FieldReference ImportReference(SR.FieldInfo field)
 {
     return(ImportReference(field, null));
 }
Ejemplo n.º 42
0
        private static object CopyOjbect(object obj)
        {
            if (obj == null)
            {
                return(null);
            }

            //拷贝目标
            Object targetDeepCopyObj;

            //元类型
            Type targetType = obj.GetType();

            //值类型
            if (targetType.IsValueType == true)
            {
                targetDeepCopyObj = obj;
            }
            //引用类型
            else
            {
                //创建引用对象
                targetDeepCopyObj = System.Activator.CreateInstance(targetType);

                //获取引用对象的所有公共成员
                System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();

                foreach (System.Reflection.MemberInfo member in memberCollection)
                {
                    //拷贝字段
                    if (member.MemberType == System.Reflection.MemberTypes.Field)
                    {
                        System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;
                        Object fieldValue = field.GetValue(obj);
                        if (fieldValue is ICloneable)
                        {
                            field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());
                        }
                        else
                        {
                            field.SetValue(targetDeepCopyObj, CopyOjbect(fieldValue));
                        }
                    }//拷贝属性
                    else if (member.MemberType == System.Reflection.MemberTypes.Property)
                    {
                        System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;

                        MethodInfo info = myProperty.GetSetMethod(false);
                        if (info != null)
                        {
                            try
                            {
                                object propertyValue = myProperty.GetValue(obj, null);
                                if (propertyValue is ICloneable)
                                {
                                    myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);
                                }
                                else
                                {
                                    myProperty.SetValue(targetDeepCopyObj, CopyOjbect(propertyValue), null);
                                }
                            }
                            catch
                            {
                                //TODO
                                //输出你要处理的异常代码
                            }
                        }
                    }
                }
            }
            return(targetDeepCopyObj);
        }
Ejemplo n.º 43
0
        private static CudafyModule DoCudafy(CudafyModule cm, params Type[] types)
        {
            MemoryStream output   = new MemoryStream();
            var          outputSw = new StreamWriter(output);

            MemoryStream structs    = new MemoryStream();
            var          structsSw  = new StreamWriter(structs);
            var          structsPto = new PlainTextOutput(structsSw);

            MemoryStream declarations    = new MemoryStream();
            var          declarationsSw  = new StreamWriter(declarations);
            var          declarationsPto = new PlainTextOutput(declarationsSw);

            MemoryStream code    = new MemoryStream();
            var          codeSw  = new StreamWriter(code);
            var          codePto = new PlainTextOutput(codeSw);

            bool isDummy = false;
            eCudafyDummyBehaviour behaviour = eCudafyDummyBehaviour.Default;

            Dictionary <string, ModuleDefinition> modules = new Dictionary <string, ModuleDefinition>();

            var compOpts = new DecompilationOptions {
                FullDecompilation = true
            };

            CUDALanguage.Reset();
            bool firstPass = true;

            if (cm == null)
            {
                cm = new CudafyModule();// #######!!!
            }
            else
            {
                firstPass = false;
            }

            // Test structs
            //foreach (var strct in types.Where(t => !t.IsClass))
            //    if (strct.GetCustomAttributes(typeof(CudafyAttribute), false).Length == 0)
            //        throw new CudafyLanguageException(CudafyLanguageException.csCUDAFY_ATTRIBUTE_IS_MISSING_ON_X, strct.Name);

            IEnumerable <Type> typeList = GetWithNestedTypes(types);

            foreach (var type in typeList)
            {
                if (!modules.ContainsKey(type.Assembly.Location))
                {
                    modules.Add(type.Assembly.Location, ModuleDefinition.ReadModule(type.Assembly.Location));
                }
            }

            // Additional loop to compile in order
            foreach (var requestedType in typeList)
            {
                foreach (var kvp in modules)
                {
                    foreach (var td in kvp.Value.Types)
                    {
                        List <TypeDefinition> tdList = new List <TypeDefinition>();
                        tdList.Add(td);
                        tdList.AddRange(td.NestedTypes);

                        Type type = null;
                        foreach (var t in tdList)
                        {
                            //type = typeList.Where(tt => tt.FullName.Replace("+", "") == t.FullName.Replace("/", "")).FirstOrDefault();
                            // Only select type if this matches the requested type (to ensure order is maintained).
                            type = requestedType.FullName.Replace("+", "") == t.FullName.Replace("/", "") ? requestedType : null;

                            if (type == null)
                            {
                                continue;
                            }
                            Debug.WriteLine(t.FullName);
                            // Types
                            var attr = t.GetCudafyType(out isDummy, out behaviour);
                            if (attr != null)
                            {
                                _cl.DecompileType(t, structsPto, compOpts);
                                if (firstPass)
                                {
                                    cm.Types.Add(type.FullName.Replace("+", ""), new KernelTypeInfo(type, isDummy, behaviour));// #######!!!
                                }
                            }
                            else if (t.Name == td.Name)
                            {
                                // Fields
                                foreach (var fi in td.Fields)
                                {
                                    attr = fi.GetCudafyType(out isDummy, out behaviour);
                                    if (attr != null)
                                    {
                                        VerifyMemberName(fi.Name);
                                        System.Reflection.FieldInfo fieldInfo = type.GetField(fi.Name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                                        if (fieldInfo == null)
                                        {
                                            throw new CudafyLanguageException(CudafyLanguageException.csX_ARE_NOT_SUPPORTED, "Non-static fields");
                                        }
                                        int[] dims = _cl.GetFieldInfoDimensions(fieldInfo);
                                        _cl.DecompileCUDAConstantField(fi, dims, codePto, compOpts);
                                        var kci = new KernelConstantInfo(fi.Name, fieldInfo, isDummy);
                                        if (firstPass)
                                        {
                                            cm.Constants.Add(fi.Name, kci);// #######!!!
                                        }
                                        CUDALanguage.AddConstant(kci);
                                    }
                                }
#warning TODO Only Global Methods can be called from host
#warning TODO For OpenCL may need to do Methods once all Constants have been handled
                                // Methods
                                foreach (var med in td.Methods)
                                {
                                    attr = med.GetCudafyType(out isDummy, out behaviour);
                                    if (attr != null)
                                    {
                                        if (!med.IsStatic)
                                        {
                                            throw new CudafyLanguageException(CudafyLanguageException.csX_ARE_NOT_SUPPORTED, "Non-static methods");
                                        }
                                        _cl.DecompileMethodDeclaration(med, declarationsPto, new DecompilationOptions {
                                            FullDecompilation = false
                                        });
                                        _cl.DecompileMethod(med, codePto, compOpts);
                                        MethodInfo mi = type.GetMethod(med.Name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                                        if (mi == null)
                                        {
                                            continue;
                                        }
                                        VerifyMemberName(med.Name);
                                        eKernelMethodType kmt = eKernelMethodType.Device;
                                        kmt = GetKernelMethodType(attr, mi);
                                        if (firstPass)
                                        {
                                            cm.Functions.Add(med.Name, new KernelMethodInfo(type, mi, kmt, isDummy, behaviour, cm));// #######!!!
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            codeSw.Flush();

            if (CudafyTranslator.Language == eLanguage.OpenCL)
            {
                outputSw.WriteLine("#if defined(cl_khr_fp64)");
                outputSw.WriteLine("#pragma OPENCL EXTENSION cl_khr_fp64: enable");
                outputSw.WriteLine("#elif defined(cl_amd_fp64)");
                outputSw.WriteLine("#pragma OPENCL EXTENSION cl_amd_fp64: enable");
                outputSw.WriteLine("#endif");
            }

            foreach (var oh in CUDALanguage.OptionalHeaders)
            {
                if (oh.Used && !oh.AsResource)
                {
                    outputSw.WriteLine(oh.IncludeLine);
                }
                else if (oh.Used)
                {
                    outputSw.WriteLine(GetResourceString(oh.IncludeLine));
                }
            }
            foreach (var oh in CUDALanguage.OptionalFunctions)
            {
                if (oh.Used)
                {
                    outputSw.WriteLine(oh.Code);
                }
            }

            declarationsSw.WriteLine();
            declarationsSw.Flush();

            structsSw.WriteLine();
            structsSw.Flush();

            foreach (var def in cm.GetDummyDefines())
            {
                outputSw.WriteLine(def);
            }
            foreach (var inc in cm.GetDummyStructIncludes())
            {
                outputSw.WriteLine(inc);
            }
            foreach (var inc in cm.GetDummyIncludes())
            {
                outputSw.WriteLine(inc);
            }
            outputSw.Flush();

            output.Write(structs.GetBuffer(), 0, (int)structs.Length);
            output.Write(declarations.GetBuffer(), 0, (int)declarations.Length);
            output.Write(code.GetBuffer(), 0, (int)code.Length);
            outputSw.Flush();
#if DEBUG
            using (FileStream fs = new FileStream("output.cu", FileMode.Create))
            {
                fs.Write(output.GetBuffer(), 0, (int)output.Length);
            }
#endif
            String s = Encoding.UTF8.GetString(output.GetBuffer(), 0, (int)output.Length);
            //cm.SourceCode = s;// #######!!!
            var scf = new SourceCodeFile(s, Language, _architecture);
            cm.AddSourceCodeFile(scf);
            return(cm);
        }
Ejemplo n.º 44
0
        private void DrawNormalValue(System.Reflection.FieldInfo filed, Rect rect, object o)
        {
            switch (filed.FieldType.ToString())
            {
            case "UnityEngine.Vector3":
                filed.SetValue(o, EditorGUI.Vector3Field(rect, "", (Vector3)filed.GetValue(o)));
                rect = GetGUILeftScrollAreaRect(60, rect.width, rect.height, true);
                Transform t = null;
                t = EditorGUI.ObjectField(rect, t, typeof(Transform), true) as Transform;
                if (t)
                {
                    filed.SetValue(o, t.position);
                }
                break;

            case "UnityEngine.Vector2":
                filed.SetValue(o, EditorGUI.Vector2Field(rect, "", (Vector2)filed.GetValue(o)));
                break;

            case "System.Single":
                filed.SetValue(o, EditorGUI.FloatField(rect, (float)filed.GetValue(o)));
                break;

            case "System.Int32":
                filed.SetValue(o, EditorGUI.IntField(rect, (int)filed.GetValue(o)));
                break;

            case "System.String":
                filed.SetValue(o, EditorGUI.TextField(rect, (string)filed.GetValue(o)));
                break;

            case "System.Boolean":
                filed.SetValue(o, EditorGUI.Toggle(rect, (bool)filed.GetValue(o)));
                break;

            case "System.String[]":
                //高级编辑功能
                rect = GetGUILeftScrollAreaRect(80, 90, 20, false);
                if (GUI.Button(rect, "<color=#00FF00>Advance Edit</color>", ResourcesManager.GetInstance.skin.button))
                {
                    AdvanceStringArrayEditor.Open(o, filed);
                }

                //通常编辑功能
                string[] array = filed.GetValue(o) as string[];
                rect = GetGUILeftScrollAreaRect(175, 20, 18);
                LeftHeightSpace(6);
                if (GUI.Button(rect, "+", ResourcesManager.GetInstance.skin.button))
                {
                    Array.Resize <string>(ref array, array.Length + 1);
                }
                if (array == null)
                {
                    array = new string[] { }
                }
                ;
                for (int j = 0; j < array.Length; j++)
                {
                    rect     = GetGUILeftScrollAreaRect(10, 160, 18, false);
                    array[j] = EditorGUI.TextField(rect, (string)array[j]);
                    rect     = GetGUILeftScrollAreaRect(175, 20, 18);
                    if (GUI.Button(rect, "-", ResourcesManager.GetInstance.skin.button))
                    {
                        for (int n = j; n < array.Length - 1; n++)
                        {
                            array[j] = array[j + 1];
                        }
                        Array.Resize <string>(ref array, array.Length - 1);
                        break;
                    }
                    LeftHeightSpace(2);
                }
                filed.SetValue(o, array);
                break;

            default:
                if (filed.FieldType.BaseType.ToString() == "System.Enum")
                {
                    //System.Enum.Parse(filed.FieldType.DeclaringType, (string)filed.GetValue(_currentNode));
                    filed.SetValue(o, EditorGUI.EnumPopup(rect, (System.Enum)filed.GetValue(o)));
                }
                else
                {
                    EditorGUI.LabelField(rect, "Not Deal Object.");
                }
                break;
            }
        }
Ejemplo n.º 45
0
 public static FieldReference ImportEx(this ModuleDefinition module, System.Reflection.FieldInfo field, IGenericParameterProvider context)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 46
0
        private Type GenerateOneToOneColumn(IndentingTextWriter writer, string className, Type columnType,
                                            System.Reflection.FieldInfo fieldInfo, ArgumentAttribute inputAttr, Type type, bool isArray)
        {
            var fieldName     = CSharpGeneratorUtils.Capitalize(inputAttr.Name ?? fieldInfo.Name);
            var generatedType = _generatedClasses.GetApiName(type, "");

            writer.WriteLine($"public {className}()");
            writer.WriteLine("{");
            writer.WriteLine("}");
            writer.WriteLine("");
            writer.WriteLine($"public {className}(params string[] input{fieldName}s)");
            writer.WriteLine("{");
            writer.Indent();
            writer.WriteLine($"if (input{fieldName}s != null)");
            writer.WriteLine("{");
            writer.Indent();
            writer.WriteLine($"foreach (string input in input{fieldName}s)");
            writer.WriteLine("{");
            writer.Indent();
            writer.WriteLine($"Add{fieldName}(input);");
            writer.Outdent();
            writer.WriteLine("}");
            writer.Outdent();
            writer.WriteLine("}");
            writer.Outdent();
            writer.WriteLine("}");
            writer.WriteLine("");
            writer.WriteLine($"public {className}(params (string inputColumn, string outputColumn)[] inputOutput{fieldName}s)");
            writer.WriteLine("{");
            writer.Indent();
            writer.WriteLine($"if (inputOutput{fieldName}s != null)");
            writer.WriteLine("{");
            writer.Indent();
            writer.WriteLine($"foreach (var inputOutput in inputOutput{fieldName}s)");
            writer.WriteLine("{");
            writer.Indent();
            writer.WriteLine($"Add{fieldName}(inputOutput.outputColumn, inputOutput.inputColumn);");
            writer.Outdent();
            writer.WriteLine("}");
            writer.Outdent();
            writer.WriteLine("}");
            writer.Outdent();
            writer.WriteLine("}");
            writer.WriteLine("");
            writer.WriteLine($"public void Add{fieldName}(string inputColumn)");
            writer.WriteLine("{");
            writer.Indent();
            if (isArray)
            {
                writer.WriteLine($"var list = {fieldName} == null ? new List<{generatedType}>() : new List<{generatedType}>({fieldName});");
                writer.WriteLine($"list.Add(OneToOneColumn<{generatedType}>.Create(inputColumn));");
                writer.WriteLine($"{fieldName} = list.ToArray();");
            }
            else
            {
                writer.WriteLine($"{fieldName} = OneToOneColumn<{generatedType}>.Create(inputColumn);");
            }
            writer.Outdent();
            writer.WriteLine("}");
            writer.WriteLine();
            writer.WriteLine($"public void Add{fieldName}(string outputColumn, string inputColumn)");
            writer.WriteLine("{");
            writer.Indent();
            if (isArray)
            {
                writer.WriteLine($"var list = {fieldName} == null ? new List<{generatedType}>() : new List<{generatedType}>({fieldName});");
                writer.WriteLine($"list.Add(OneToOneColumn<{generatedType}>.Create(outputColumn, inputColumn));");
                writer.WriteLine($"{fieldName} = list.ToArray();");
            }
            else
            {
                writer.WriteLine($"{fieldName} = OneToOneColumn<{generatedType}>.Create(outputColumn, inputColumn);");
            }
            writer.Outdent();
            writer.WriteLine("}");
            writer.WriteLine();

            Contracts.Assert(columnType == null);

            columnType = type;
            return(columnType);
        }
Ejemplo n.º 47
0
 public FieldReference ImportField(SR.FieldInfo field)
 {
     return(ImportField(field, default(ImportGenericContext)));
 }
Ejemplo n.º 48
0
 internal PropInfo(object obj, System.Reflection.FieldInfo field)
 {
     this.obj   = obj;
     this.field = field;
 }
Ejemplo n.º 49
0
        public override void Execute(MethodInfo aMethod, ILOpCode aOpCode)
        {
            var xType   = aMethod.MethodBase.DeclaringType;
            var xOpCode = (ILOpCodes.OpField)aOpCode;

            SysReflection.FieldInfo xField = xOpCode.Value;
            // call cctor:
            var xCctor = (xField.DeclaringType.GetConstructors(BindingFlags.Static | BindingFlags.NonPublic) ?? new ConstructorInfo[0]).SingleOrDefault();

            if (xCctor != null && xCctor.DeclaringType != aMethod.MethodBase.DeclaringType)
            {
                new CPUx86.Call {
                    DestinationLabel = LabelName.Get(xCctor)
                };
                ILOp.EmitExceptionLogic(Assembler, aMethod, aOpCode, true, null, ".AfterCCTorExceptionCheck");
                new Label(".AfterCCTorExceptionCheck");
            }

            //int aExtraOffset;// = 0;
            //bool xNeedsGC = xField.FieldType.IsClass && !xField.FieldType.IsValueType;
            uint xSize = SizeOfType(xField.FieldType);

            //if( xNeedsGC )
            //{
            //    aExtraOffset = 12;
            //}
            new Comment(Assembler, "Type = '" + xField.FieldType.FullName /*+ "', NeedsGC = " + xNeedsGC*/);

            uint xOffset = 0;

            var xFields = xField.DeclaringType.GetFields();

            foreach (SysReflection.FieldInfo xInfo in xFields)
            {
                if (xInfo == xField)
                {
                    break;
                }

                xOffset += SizeOfType(xInfo.FieldType);
            }
            string xDataName = DataMember.GetStaticFieldName(xField);

            for (int i = 0; i < (xSize / 4); i++)
            {
                new CPUx86.Pop {
                    DestinationReg = CPUx86.Registers.EAX
                };
                new CPUx86.Mov {
                    DestinationRef = Cosmos.Assembler.ElementReference.New(xDataName, i * 4), DestinationIsIndirect = true, SourceReg = CPUx86.Registers.EAX
                };
            }
            switch (xSize % 4)
            {
            case 1:
            {
                new CPUx86.Pop {
                    DestinationReg = CPUx86.Registers.EAX
                };
                new CPUx86.Mov {
                    DestinationRef = Cosmos.Assembler.ElementReference.New(xDataName, ( int )((xSize / 4) * 4)), DestinationIsIndirect = true, SourceReg = CPUx86.Registers.AL
                };
                break;
            }

            case 2:
            {
                new CPUx86.Pop {
                    DestinationReg = CPUx86.Registers.EAX
                };
                new CPUx86.Mov {
                    DestinationRef = Cosmos.Assembler.ElementReference.New(xDataName, ( int )((xSize / 4) * 4)), DestinationIsIndirect = true, SourceReg = CPUx86.Registers.AX
                };
                break;
            }

            case 0:
            {
                break;
            }

            default:
                //EmitNotImplementedException(Assembler, GetServiceProvider(), "Ldsfld: Remainder size " + (xSize % 4) + " not supported!", mCurLabel, mMethodInformation, mCurOffset, mNextLabel);
                throw new NotImplementedException();
                //break;
            }
        }
Ejemplo n.º 50
0
        /// <summary>
        /// Set the value of one property of this object.
        /// </summary>
        /// <param name="name">Name of the field to be set.</param>
        /// <param name="value">String representation of the value of the field.</param>
        /// <returns>True of the field could be set with the given value. False if there is no field with the given name.</returns>
        public bool setSetting(string name, string value)
        {
            // Replace '-' in ml settings name with underscore since '-' isnt a valid symbol for names.
            // Now both underscore and '-' are supported for uniform naming.
            if (name.Contains("-"))
            {
                name = name.Replace("-", "_");
            }

            System.Reflection.FieldInfo fi = this.GetType().GetField(name);

            if (fi == null)
            {
                return(false);
            }

            string asa = fi.FieldType.FullName;

            // The processing of the blacklist
            if (name.ToLower().Equals("blacklisted"))
            {
                String[] optionsToBlacklist = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (String option in optionsToBlacklist)
                {
                    this.blacklisted.Add(option.ToLower());
                }
                this.blacklisted = this.blacklisted.Distinct().ToList();
                return(true);
            }
            if (fi.FieldType.FullName.Equals("System.Boolean"))
            {
                if (value.ToLowerInvariant() == "true" || value.ToLowerInvariant() == "false")
                {
                    fi.SetValue(this, Convert.ToBoolean(value));
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            if (fi.FieldType.FullName.Equals("System.Int32"))
            {
                int  n;
                bool isNumeric = int.TryParse(value, out n);

                if (isNumeric)
                {
                    fi.SetValue(this, n);
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            if (fi.FieldType.FullName.Equals("System.Int64"))
            {
                int  n;
                bool isNumeric = int.TryParse(value, out n);

                if (isNumeric)
                {
                    fi.SetValue(this, n);
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            if (fi.FieldType.FullName.Equals("MachineLearning.Learning.ML_Settings+LossFunction"))
            {
                if (value.Equals("RELATIVE"))
                {
                    fi.SetValue(this, LossFunction.RELATIVE);
                    return(true);
                }
                if (value.Equals("LEASTSQUARES"))
                {
                    fi.SetValue(this, LossFunction.LEASTSQUARES);
                    return(true);
                }
                if (value.Equals("ABSOLUTE"))
                {
                    fi.SetValue(this, LossFunction.ABSOLUTE);
                    return(true);
                }
            }
            if (fi.FieldType.FullName.Equals("System.Double"))
            {
                double n;
                bool   isNumeric = double.TryParse(value, out n);

                if (isNumeric)
                {
                    fi.SetValue(this, n);
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            if (fi.FieldType.FullName.Equals("System.TimeSpan"))
            {
                TimeSpan n;
                bool     isValid = TimeSpan.TryParse(value, out n);

                if (isValid)
                {
                    fi.SetValue(this, n);
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            if (fi.FieldType.FullName.Equals("MachineLearning.Learning.ML_Settings+ScoreMeasure"))
            {
                ScoreMeasure parsedValue;
                try
                {
                    parsedValue = (ScoreMeasure)Enum.Parse(typeof(ScoreMeasure), value.ToUpperInvariant());
                }
                catch (ArgumentException)
                {
                    return(false);
                }
                fi.SetValue(this, parsedValue);
                return(true);
            }


            return(false);
        }
Ejemplo n.º 51
0
 public virtual FieldReference ImportReference(SR.FieldInfo field, IGenericParameterProvider context)
 {
     Mixin.CheckField(field);
     return(ImportField(field, ImportGenericContext.For(context)));
 }
Ejemplo n.º 52
0
    /// <summary>
    /// 处理一张表 Handle A table.
    /// </summary>
    /// <param name="result">Result.</param>
    public static bool HandleATable(DataTable result)
    {
        Debug.Log(result.TableName);

        //创建这个类
        Type t = Type.GetType(GetClassNameByName(result.TableName));

        if (t == null)
        {
            Debug.Log("the type is null  : " + result.TableName);
            return(false);
        }

        int columns = result.Columns.Count;
        int rows    = result.Rows.Count;

        //行数从0开始  第0行为注释
        int fieldsRow      = 1;   //字段名所在行数
        int contentStarRow = 2;   //内容起始行数

        //获取所有字段
        string[] tableFields = new string[columns];

        for (int j = 0; j < columns; j++)
        {
            tableFields[j] = result.Rows[fieldsRow][j].ToString();
            //Debuger.Log(tableFields[j]);
        }

        //存储表内容的字典
        List <ConfigClass> datalist = new List <ConfigClass>();

        //遍历所有内容
        for (int i = contentStarRow; i < rows; i++)
        {
            ConfigClass o = Activator.CreateInstance(t) as ConfigClass;

            for (int j = 0; j < columns; j++)
            {
                System.Reflection.FieldInfo info = o.GetType().GetField(tableFields[j]);

                if (info == null)
                {
                    continue;
                }

                string val = result.Rows[i][j].ToString();

                if (info.FieldType == typeof(int))
                {
                    info.SetValue(o, int.Parse(val));
                }
                else if (info.FieldType == typeof(float))
                {
                    info.SetValue(o, float.Parse(val));
                }
                else
                {
                    info.SetValue(o, val);
                }
                //Debuger.Log(val);
            }

            datalist.Add(o);
        }

        SaveTableData(datalist, result.TableName + ".msconfig");
        return(true);
    }
Ejemplo n.º 53
0
 public void OnValueChanged(System.Reflection.FieldInfo field, object oldValue, object newValue)
 {
 }