Пример #1
0
        } //end of method

        public static object GetInstanceMember(System.Type t, string strMember, object objInstance)
        {
            BindingFlags eFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
            FieldInfo fInfo = t.GetField(strMember, eFlags);

            return fInfo.GetValue(objInstance);
        }
        private string ResolveName(string name, ref System.Type type)
        {
            if (_caseSensitive)
                return name;

            var property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase);

            if (property != null)
            {
                type = property.PropertyType;
                return property.Name;
            }

            var field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase);

            if (field != null)
            {
                type = field.FieldType;
                return field.Name;
            }

            throw new QueryException(String.Format(
                "Cannot resolve name '{0}' on '{1}'", name, type)
            );
        }
Пример #3
0
        internal static Enum GetEnumValue(System.Type enumType, string s)
        {
            //TODO: COMENTADO. SEGUN LAS REFERENCIAS DEL PROYECTO, TODOS LOS TIPOS
            //QUE INVOCAN A ESTE METODO SON SIEMPRE DE TIPO "ENUM"
            //if (!enumType.IsEnum)
            //	throw new ArgumentException("Not an enumeration type", "enumType");

            // We only want to parse single named constants
            if (s.Length > 0 && char.IsLetter(s[0]) && s.IndexOf(',') < 0)
            {
                s = s.Replace('-', '_');

            #if NETCF_1_0
                FieldInfo field = enumType.GetField(s, BindingFlags.Static | BindingFlags.Public);
                if (field != null)
                {
                    return (Enum)field.GetValue(null);
                }
            #else
                return (Enum)Enum.Parse(enumType, s, false);
            #endif
            }

            throw new ArgumentException();
        }
Пример #4
0
 public static string GetEnumDescription(System.Type value, string name)
 {
     FieldInfo fi= value.GetField(name);
     DescriptionAttribute[] attributes =
     (DescriptionAttribute[])fi.GetCustomAttributes(
     typeof(DescriptionAttribute), false);
     return (attributes.Length>0)?attributes[0].Description:name;
 }
Пример #5
0
 private void FillItemsFromType(System.Type t)
 {
     if (t.get_IsEnum())
     {
         foreach (object obj2 in System.Enum.GetValues(t))
         {
             DescriptionAttribute customAttribute = (DescriptionAttribute) System.Attribute.GetCustomAttribute(t.GetField(System.Enum.GetName(t, obj2)), typeof(DescriptionAttribute));
             string text = customAttribute.get_Description() ?? obj2.ToString();
             base.Items.Add(new EnumComboBoxItem(obj2, text));
         }
     }
 }
        public static FieldInfo FindFieldInherited(System.Type startType, string fieldName)
        {
            if (startType == typeof(UnityEngine.MonoBehaviour) || startType == null)
                return null;

            // Copied fields can be restricted with BindingFlags
            var field = startType.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            if (field != null)
                return field;

            // Keep going untill we hit UnityEngine.MonoBehaviour type.
            return FindFieldInherited(startType.BaseType, fieldName);
        }
Пример #7
0
 /// <summary>
 /// 获取指定枚举值的描述信息
 /// </summary>
 /// <param name="t">枚举类型</param>
 /// <param name="v">枚举值</param>
 /// <returns></returns>
 public static string GetDescription(System.Type t, object v)
 {
     try
     {
         FieldInfo oFieldInfo = t.GetField(GetName(t, v));
         DescriptionAttribute[] attributes = (DescriptionAttribute[])oFieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
         return (attributes.Length > 0) ? attributes[0].Description : GetName(t, v);
     }
     catch
     {
         return "未知";
     }
 }
Пример #8
0
        private static void initFields(FPod pod, System.Type type)
        {
            FLiterals literals = pod.readLiterals();

              for (int i=0; i<literals.m_ints.size(); i++)
            type.GetField("I"+i).SetValue(null, literals.m_ints.get(i));
              for (int i=0; i<literals.m_floats.size(); i++)
            type.GetField("F"+i).SetValue(null, literals.m_floats.get(i));
              for (int i=0; i<literals.m_decimals.size(); i++)
            type.GetField("D"+i).SetValue(null, literals.m_decimals.get(i));
              for (int i=0; i<literals.m_strs.size(); i++)
            type.GetField("S"+i).SetValue(null, literals.m_strs.get(i));
              for (int i=0; i<literals.m_durations.size(); i++)
            type.GetField("Dur"+i).SetValue(null, literals.m_durations.get(i));
              for (int i=0; i<literals.m_uris.size(); i++)
            type.GetField("U"+i).SetValue(null, literals.m_uris.get(i));
        }
Пример #9
0
        /// <summary>
        /// Resolve a query name to an entity name.
        /// </summary>
        /// <param name="name">The name to map.</param>
        /// <param name="type">The type of the entity to map the name for.</param>
        /// <param name="caseSensitive">Whether the <param name="name"> parameter must be treated case sensitive.</param></param>
        /// <returns>The mapped name and member type or null when the name could not be resolved.</returns>
        public virtual ResolvedName ResolveName(string name, System.Type type, bool caseSensitive)
        {
            var bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

            if (!caseSensitive)
                bindingFlags |= BindingFlags.IgnoreCase;

            var property = type.GetProperty(name, bindingFlags);

            if (property != null)
                return new ResolvedName(property.PropertyType, property.Name);

            var field = type.GetField(name, bindingFlags);

            if (field != null)
                return new ResolvedName(field.FieldType, field.Name);

            return null;
        }
        public FieldPropertyInfo(System.Type type, string fieldPropertyName)
        {
            this.memberInfo = null;
            FieldInfo field = type.GetField(fieldPropertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
            if (field != null)
            {
                this.memberInfo = field;
            }
            else
            {
                PropertyInfo property = type.GetProperty(fieldPropertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                if (property != null)
                {
                    this.memberInfo = property;
                }
            }
            
			throw new Exception(string.Concat(new object[] { "FieldPropertyInfo: ", type, ", ", fieldPropertyName }));
		}
        public static object GetField(object target, System.Type type, string fieldName)
        {
            PropertyInfo property = type.GetProperty(fieldName);
            FieldInfo field = type.GetField(fieldName);

            if( null == property && null == field){
                XLogger.Log(type.Name + "." + " not contain " + fieldName);
                return null;
            }
            object returnValue = null;
            if( null != property )
                returnValue = property.GetValue(target, null);
            else if( null != field)
                returnValue = field.GetValue(target);
            if( null == returnValue){
                XLogger.Log(type.Name + "." + property.Name + " is null.");
                return null;
            }
            return returnValue;
        }
Пример #12
0
        private static System.Data.Common.DbProviderFactory GetFactory(System.Type type)
        {
            if (type != null && type.IsSubclassOf(typeof(System.Data.Common.DbProviderFactory)))
            {
                // Provider factories are singletons with Instance field having
                // the sole instance
                System.Reflection.FieldInfo field = type.GetField("Instance"
                    , System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static
                );

                if (field != null)
                {
                    return (System.Data.Common.DbProviderFactory)field.GetValue(null);
                    //return field.GetValue(null) as DbProviderFactory;
                } // End if (field != null)

            } // End if (type != null && type.IsSubclassOf(typeof(System.Data.Common.DbProviderFactory)))

            throw new System.Configuration.ConfigurationErrorsException("DataProvider is missing!");
            //throw new System.Configuration.ConfigurationException("DataProvider is missing!");
        }
Пример #13
0
        internal static Enum GetEnumValue(System.Type enumType, string s)
        {
            //			if (!enumType.IsEnum())
            //				throw new ArgumentException("Not an enumeration type", "enumType");

            // We only want to parse single named constants
            if (s.Length > 0 && char.IsLetter(s[0]) && s.IndexOf(',') < 0)
            {
                s = s.Replace('-', '_');

            #if NETCF_1_0
                FieldInfo field = enumType.GetField(s, BindingFlags.Static | BindingFlags.Public);
                if (field != null)
                {
                    return (Enum)field.GetValue(null);
                }
            #else
                return (Enum)Enum.Parse(enumType, s, false);
            #endif
            }

            throw new ArgumentException();
        }
Пример #14
0
		private static FieldInfo GetField(System.Type type, string fieldName, System.Type originalType)
		{
			if (type == null || type == typeof(object))
			{
				// the full inheritance chain has been walked and we could
				// not find the Field
				throw new PropertyNotFoundException(originalType, fieldName);
			}

			FieldInfo field =
				type.GetField(fieldName,
							  BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
			if (field == null)
			{
				// recursively call this method for the base Type
				field = GetField(type.BaseType, fieldName, originalType);
			}

			return field;
		}
Пример #15
0
 private bool IsWindowAllowed(System.Type ttsformtype)
 {
     System.Reflection.FieldInfo field = ttsformtype.GetField("TTSWindowType", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
     return !(field == null) && Game.State.General.AllowedWindows.HasFlag((WindowType)field.GetValue(null));
 }
Пример #16
0
		//make sure the class has the proper declaration.
		public string _get_primary_key_name(System.Type t)
		{
			object[] attributes = t.GetCustomAttributes(typeof(OOD.SchemaDefine),true);
			if (attributes != null && attributes.Length == 1)
			{
				SchemaDefine declared = (SchemaDefine)attributes[0];
				string pk = declared.PrimaryKey;
				FieldInfo pkField = t.GetField(pk, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
				if (pkField == null)
					throw new OOD.Exception.MissingPrimaryKey(
						this,
						"Primary key field is not found.");

				if (pkField.IsStatic || pkField.IsInitOnly)
					throw new OOD.Exception.MissingPrimaryKey(
						this,
						"Primary key can not defined on the static field member or initialize only field.");

				return pk;
			}
			else
				throw new OOD.Exception.MissingPrimaryKey(
					this,
					"Primary key is not defined.");

		}
		private static MemberInfo GetField(System.Type type, string fieldName)
		{
			if (type == typeof (object) || type == null)
			{
				return null;
			}
			MemberInfo member = type.GetField(fieldName, FieldBindingFlag) ?? GetField(type.BaseType, fieldName);
			return member;
		}
        private void SetMappedMembers(System.Type type)
        {
            var propertyMappings = from mapping in mappings
                                   let hbmClasses = from hbmClass in mapping.RootClasses where hbmClass.Name == type.Name select hbmClass
                                   from rootClass in hbmClasses
                                   where rootClass != null
                                   from propertyMapping in rootClass.Items.OfType<IEntityPropertyMapping>()
                                   select propertyMapping;

            foreach (var propertyMapping in propertyMappings)
            {
                if (propertyMapping.Access != null && propertyMapping.Access == "field")
                {
                    var fieldInfo = type.GetField(propertyMapping.Name, BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

                    mappedMembers.Add(new LocationInfo(fieldInfo));
                }
                else
                    mappedMembers.Add(new LocationInfo(type.GetProperty(propertyMapping.Name)));
            }
        }
        /// <summary>
        /// Helper method to find the Field.
        /// </summary>
        /// <param name="type">The <see cref="System.Type"/> to find the Field in.</param>
        /// <param name="fieldName">The name of the Field to find.</param>
        /// <returns>
        /// The <see cref="FieldInfo"/> for the field.
        /// </returns>
        /// <exception cref="PropertyNotFoundException">
        /// Thrown when a field could not be found.
        /// </exception>
        internal static FieldInfo GetField(System.Type type, string fieldName)
        {
            if (type == null || type == typeof(object))
            {
                // the full inheritance chain has been walked and we could
                // not find the Field
                return null;
            }

            FieldInfo field = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
            if (field == null)
            {
                // recursively call this method for the base Type
                field = GetField(type.BaseType, fieldName);
            }

            return field;
        }
Пример #20
0
	// Attempt to locate the member as a field, and deal with it based on the given parameters
	// Returns: boolean indicating whether the command was handled here
	public static bool CallField(System.Type targetClass, string varName, string parameters) {
		// Attempt to find the field
		FieldInfo targetVar = targetClass.GetField(varName, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
		object targetInstance = null;
		if(targetVar == null) {
			targetInstance = GetMainOfClass(targetClass);
			if(targetInstance != null) {
				targetVar = targetClass.GetField(varName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
			}
		}
		if(targetVar == null || !IsAccessible(targetVar)) { return false; } // Fail: Couldn't find field, or it's marked inaccessible
		// If field is found, deal with it appropriately based on the parameters given
		if(parameters == null || parameters.Length < 1) {
			string output = GetFieldValue(targetInstance, targetVar);
			if(output == null) { return false; } // Fail: Field is not of a supported type
			Echo(varName + " is " + output);
			return true; // Success: Value is printed when no parameters given
		}
		if(IsCheat(targetVar) && !cheats) {
			PrintCheatMessage(targetVar.Name);
		} else {
			if(!SetFieldValue(targetInstance, targetVar, parameters.SplitUnlessInContainer(' ', '\"'))) {
				Echo("Invalid " + targetVar.FieldType.Name + ": " + parameters);
			}
		}
		return true; // Success: Whether or not the field could be set, the user is notified and the case is handled
	}
        private static DependencyProperty ValidateAndRegister(string name, System.Type propertyType, System.Type ownerType, PropertyMetadata defaultMetadata, System.Type validatorType, bool isRegistered)
        {
            if (name == null)
                throw new ArgumentNullException("name");

            if (name.Length == 0)
                throw new ArgumentException(SR.GetString(SR.Error_EmptyArgument), "name");

            if (propertyType == null)
                throw new ArgumentNullException("propertyType");

            if (ownerType == null)
                throw new ArgumentNullException("ownerType");

            FieldInfo fieldInfo = null;
            bool isEvent = (typeof(System.Delegate).IsAssignableFrom(propertyType) && (defaultMetadata == null || (defaultMetadata.Options & DependencyPropertyOptions.DelegateProperty) == 0));

            // WinOE Bug 13807: events can not be meta properties.
            if (isEvent && defaultMetadata != null && defaultMetadata.IsMetaProperty)
                throw new ArgumentException(SR.GetString(SR.Error_DPAddHandlerMetaProperty), "defaultMetadata");

            //Field must exists
            if (isEvent)
                fieldInfo = ownerType.GetField(name + "Event", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.GetProperty);
            else
                fieldInfo = ownerType.GetField(name + "Property", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.GetProperty);

            if (fieldInfo == null)
            {
                string error = SR.GetString((isEvent) ? SR.Error_DynamicEventNotSupported : SR.Error_DynamicPropertyNotSupported, new object[] { ownerType.FullName, name });
                throw new ArgumentException(error, "ownerType");
            }


            PropertyMetadata metadata = null;
            object defaultValue = null;

            // Establish default metadata for all types, if none is provided
            if (defaultMetadata == null)
            {
                defaultValue = GetDefaultValue(name, propertyType, ownerType);
                metadata = new PropertyMetadata(defaultValue);
            }
            else
            {
                metadata = defaultMetadata;
                if (metadata.DefaultValue == null)
                    metadata.DefaultValue = GetDefaultValue(name, propertyType, ownerType);
            }

            DependencyProperty dependencyProperty = new DependencyProperty(name, propertyType, ownerType, metadata, validatorType, isRegistered);
            lock (((ICollection)DependencyProperty.dependencyProperties).SyncRoot)
            {
                if (DependencyProperty.dependencyProperties.ContainsKey(dependencyProperty.GetHashCode()))
                    throw new InvalidOperationException(SR.GetString(SR.Error_DPAlreadyExist, new object[] { name, ownerType.FullName }));

                DependencyProperty.dependencyProperties.Add(dependencyProperty.GetHashCode(), dependencyProperty);
            }

            return dependencyProperty;
        }
 private Skybound.ComponentModel.EnumTypeEditor.EnumValue GetEnumValue(System.ComponentModel.ITypeDescriptorContext context, System.Type enumType, string name)
 {
     System.Type type = null;
     if (context != null)
     {
         foreach (System.Attribute attribute1 in context.PropertyDescriptor.Attributes)
         {
             if ((attribute1 is Skybound.ComponentModel.EnumAttributeProviderAttribute))
             {
                 type = (attribute1 as Skybound.ComponentModel.EnumAttributeProviderAttribute).ProviderType;
                 break;
             }
         }
     }
     System.Attribute[] attributeArr1 = null;
     if (type != null)
     {
         Skybound.ComponentModel.IEnumAttributeProvider ienumAttributeProvider = System.Activator.CreateInstance(type) as Skybound.ComponentModel.IEnumAttributeProvider;
         if (ienumAttributeProvider != null)
             attributeArr1 = ienumAttributeProvider.GetAttributes(System.Enum.Parse(enumType, name, false));
     }
     if (attributeArr1 == null)
     {
         System.Reflection.FieldInfo fieldInfo = enumType.GetField(name, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
         if (System.Attribute.IsDefined(fieldInfo, typeof(System.ComponentModel.DescriptionAttribute)))
             attributeArr1 = System.Attribute.GetCustomAttributes(fieldInfo, typeof(System.ComponentModel.DescriptionAttribute));
         if (System.Attribute.IsDefined(fieldInfo, typeof(Skybound.ComponentModel.EnumValueImageProviderAttribute)))
         {
             System.Attribute[] attributeArr2 = System.Attribute.GetCustomAttributes(fieldInfo, typeof(Skybound.ComponentModel.EnumValueImageProviderAttribute));
             if (attributeArr1 != null)
             {
                 System.Attribute[] attributeArr3 = new System.Attribute[(attributeArr1.Length + attributeArr2.Length)];
                 attributeArr1.CopyTo(attributeArr3, 0);
                 attributeArr2.CopyTo(attributeArr3, attributeArr1.Length);
                 attributeArr1 = attributeArr3;
             }
         }
     }
     string s = System.String.Empty;
     System.Drawing.Image image = null;
     System.Attribute[] attributeArr4 = attributeArr1;
     for (int i = 0; i < attributeArr4.Length; i++)
     {
         System.Attribute attribute2 = attributeArr4[i];
         if ((attribute2 is System.ComponentModel.DescriptionAttribute))
         {
             s = (attribute2 as System.ComponentModel.DescriptionAttribute).Description;
         }
         else
         {
             if ((attribute2 is Skybound.ComponentModel.EnumValueImageProviderAttribute))
                 image = (attribute2 as Skybound.ComponentModel.EnumValueImageProviderAttribute).GetImage();
         }
     }
     return new Skybound.ComponentModel.EnumTypeEditor.EnumValue(name, s, image);
 }
Пример #23
0
 /// <summary>
 /// Returns the value of the static field <paramref name="fieldName"/> of <paramref name="type"/>.
 /// </summary>
 /// <param name="type">The <see cref="System.Type"/> .</param>
 /// <param name="fieldName">The name of the field in the <paramref name="type"/>.</param>
 /// <returns>The value contained in the field, or <see langword="null" /> if the type or the field does not exist.</returns>
 public static object GetConstantValue(System.Type type, string fieldName)
 {
     try
     {
         FieldInfo field = type.GetField(fieldName);
         if (field == null)
         {
             return null;
         }
         return field.GetValue(null);
     }
     catch
     {
         return null;
     }
 }
Пример #24
0
		private void CreateControlContentForSingleEntry (CVM.TableLayoutDefinition ContentInstance,
									System.Type ContentClass, Grid Parent)
			{
			Parent.Children.Clear ();
			Parent.RowDefinitions.Clear ();
			Parent.ColumnDefinitions.Clear ();
			PropertyInfo [] Properties = ContentClass.GetProperties ();
			GridLengthConverter GLConverter = new GridLengthConverter ();

			int RowIndex = 0;
			foreach (PropertyInfo PropInfo in Properties)
				{
				String LabePropertyName = PropInfo.Name;
				String OptionStringName = LabePropertyName + "_Option";
				FieldInfo OptionField = (FieldInfo)ContentClass.GetField (OptionStringName);
				String Options;
				if (OptionField != null)
					{
					Options = (String)OptionField.GetValue (ContentInstance);
					if (Options.IndexOf ("NoUpdate") != -1)
						continue;
					}
				String HelpStringName = LabePropertyName + "_Help";
				FieldInfo HelpField = (FieldInfo) ContentClass.GetField (HelpStringName);
				RowDefinition MainRow = new RowDefinition ();
				Parent.RowDefinitions.Add (MainRow);
				Grid SubGrid = new Grid ();
				Parent.Children.Add (SubGrid);
				Grid.SetRow (SubGrid, RowIndex++);
				Grid.SetColumn (SubGrid, 0);
				Label PropertyNameLabel = new Label ();
				PropertyNameLabel.Content = LabePropertyName;
				SubGrid.Children.Add (PropertyNameLabel);
				Grid.SetRow (PropertyNameLabel, 0);
				SubGrid.ColumnDefinitions.Add (new ColumnDefinition ());
				SubGrid.ColumnDefinitions [0].Width = (GridLength)GLConverter.ConvertFromString ("6" + "*");
				SubGrid.ColumnDefinitions.Add (new ColumnDefinition ());
				SubGrid.ColumnDefinitions [1].Width = (GridLength)GLConverter.ConvertFromString ("8" + "*");
				SubGrid.RowDefinitions.Add (new RowDefinition ());
				SubGrid.RowDefinitions [0].Height = (GridLength)GLConverter.ConvertFromString ("*");
				if (PropInfo.PropertyType == typeof (int))
					{
					TextBox ContentBox = CreateSimpleLine (ContentInstance, PropInfo, MainRow, SubGrid, HelpField);
					}
				if (PropInfo.PropertyType == typeof (double))
					{
					TextBox ContentBox = CreateSimpleLine (ContentInstance, PropInfo, MainRow, SubGrid, HelpField);
					}
				if (PropInfo.PropertyType == typeof (Size))
					{
					TextBox [] ContentBoxes = CreateTwoSubLines (ContentInstance, PropInfo, MainRow, SubGrid,
						new String [] { "Weite", "Höhe" }, HelpField);
					}
				if (PropInfo.PropertyType == typeof (Point))
					{
					TextBox [] ContentBoxes = CreateTwoSubLines (ContentInstance, PropInfo, MainRow, SubGrid,
						new String [] { "Links", "Oben" }, HelpField);
					}
				if (PropInfo.PropertyType == typeof (String))
					{
					TextBox ContentBox = CreateSimpleLine (ContentInstance, PropInfo, MainRow, SubGrid, HelpField);
					}
				if (PropInfo.PropertyType == typeof (bool))
					{
					RadioButton [] Buttons = CreateBoolLine (ContentInstance, PropInfo, MainRow, SubGrid,
						new String [] { "Ja", "Nein" }, HelpField);
					}
				}

			}
Пример #25
0
	private static System.Type GetBindingValueType(string path, System.Type type, GameObject gameObject, bool command, ref string tail)
	{
		tail = string.Empty;
		
		if (string.IsNullOrEmpty(path))
		{
			Debug.Log("Binding is empty for object " + GetGameObjectPath(gameObject), gameObject);
			return null;
		}
		
		var parts = path.Split('.');
		var pathMessage = "";
		for (var i = 0; i < parts.Length; ++i)
		{
			var part = parts[i];
			pathMessage += part;
						
			if (i < parts.Length - 1)
			{
				int index;
				if (int.TryParse(part, out index))
				{
					for (var j = i + 1; j < parts.Length; ++j)
						tail += parts[j] + ".";
					if (tail.Length > 0)
						tail = tail.Substring(0, tail.Length - 1);
					return type;
				}
				else
				{
					var nodeProperty = type.GetProperty(part);
					var nodeField = type.GetField(part);
					if (nodeProperty == null && nodeField == null)
					{
						Debug.LogError("Failed to resolve node in binding " + path + " in object " + GetGameObjectPath(gameObject) +
									   "\n[context type is " + type + "], error at " + pathMessage, gameObject);
						return null;
					}
					pathMessage += ".";
					if (nodeProperty != null)
						type = nodeProperty.PropertyType;
					else if (nodeField != null)
						type = nodeField.FieldType;
				}
			}
			else
			{
				if (command)
				{
					var leafCommand = type.GetMethod(part);
					if (leafCommand == null)
					{
						Debug.LogError("Failed to resolve leaf command in binding " + path + " in object " + GetGameObjectPath(gameObject) +
						               "\n[context type is " + type + "], error at " + pathMessage, gameObject);
						return null;
					}
				}
				else
				{
					var leafProperty = type.GetProperty(part);
					var leafField = type.GetField(part);
					if (leafProperty == null && leafField == null)
					{
						Debug.LogError("Failed to resolve leaf property in binding " + path + " in object " + GetGameObjectPath(gameObject) +
						               "\n[context type is " + type + "], error at " + pathMessage, gameObject);
						return null;
					}
					if (leafProperty != null)
						type = leafProperty.PropertyType;
					else if (leafField != null)
						type = leafField.FieldType;
				}
			}
		}
		return type;
	}
Пример #26
0
	// Returns: object reference to a "public static main" object of the same type as the class provided, if it exists within the class provided.
	public static object GetMainOfClass(System.Type targetClass) {
		FieldInfo mainField = targetClass.GetField("main", BindingFlags.Public | BindingFlags.Static);
		if(mainField != null && mainField.FieldType == targetClass && IsAccessible(mainField)) {
			return mainField.GetValue(null);
		}
		return null;
	}
		private static FieldInfo GetField(string lhs, System.Type type)
		{
			return type.GetField(lhs, BindingFlags.Instance | BindingFlags.NonPublic);
		}
 protected void ShowDerivedProperties(System.Type baseType, System.Type superType)
 {
   bool flag = true;
   SerializedProperty iterator = this.serializedObject.GetIterator();
   bool enterChildren = true;
   while (iterator.NextVisible(enterChildren))
   {
     System.Reflection.FieldInfo field = baseType.GetField(iterator.name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
     PropertyInfo property = baseType.GetProperty(iterator.name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
     if (field == null && superType != null)
       field = superType.GetField(iterator.name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
     if (property == null && superType != null)
       property = superType.GetProperty(iterator.name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
     if (field == null && property == null)
     {
       if (flag)
       {
         flag = false;
         EditorGUI.BeginChangeCheck();
         this.serializedObject.Update();
         EditorGUILayout.Separator();
       }
       EditorGUILayout.PropertyField(iterator, true, new GUILayoutOption[0]);
       enterChildren = false;
     }
   }
   if (flag)
     return;
   this.serializedObject.ApplyModifiedProperties();
   EditorGUI.EndChangeCheck();
 }
Пример #29
0
		/// <summary>
		/// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
		/// A parameter specifies whether the operation is case-sensitive.
		/// </summary>
		/// <param name="enumType">The <see cref="T:System.Type"/> of the enumeration.</param>
		/// <param name="value">A string containing the name or value to convert.</param>
		/// <param name="ignoreCase">If true, ignore case; otherwise, regard case.</param>
		/// <returns>An object of type enumType whose value is represented by value.</returns>
		/// <exception cref="System.ArgumentException">enumType is not an <see cref="T:System.Enum"/>.
		///  -or-  value is either an empty string ("") or only contains white space.
		///  -or-  value is a name, but not one of the named constants defined for the enumeration.</exception>
		///  <seealso cref="M:System.Enum.Parse(System.Type,System.String,System.Boolean)">System.Enum.Parse Method</seealso>
		public static object Parse(System.Type enumType, string value, bool ignoreCase)
		{
#if NETCF2
			//use intrinsic functionality in v2
			return Enum.Parse(enumType,value,ignoreCase);
#else
			//throw an exception on null value
			if(value.TrimEnd(' ')=="")
			{
				throw new ArgumentException("value is either an empty string (\"\") or only contains white space.");
			}
			else
			{
				//type must be a derivative of enum
				if(enumType.BaseType==Type.GetType("System.Enum"))
				{
					//remove all spaces
					string[] memberNames = value.Replace(" ","").Split(',');
					
					//collect the results
					//we are cheating and using a long regardless of the underlying type of the enum
					//this is so we can use ordinary operators to add up each value
					//I suspect there is a more efficient way of doing this - I will update the code if there is
					long returnVal = 0;

					//for each of the members, add numerical value to returnVal
					foreach(string thisMember in memberNames)
					{
						//skip this string segment if blank
						if(thisMember!="")
						{
							try
							{
								if(ignoreCase)
								{
									returnVal += (long)Convert.ChangeType(enumType.GetField(thisMember, BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase).GetValue(null),returnVal.GetType(), null);
								}
								else
								{
									returnVal += (long)Convert.ChangeType(enumType.GetField(thisMember, BindingFlags.Public | BindingFlags.Static).GetValue(null),returnVal.GetType(), null);
								}
							}
							catch
							{
								try
								{
									//try getting the numeric value supplied and converting it
									returnVal += (long)Convert.ChangeType(System.Enum.ToObject(enumType, Convert.ChangeType(thisMember, System.Enum.GetUnderlyingType(enumType), null)),typeof(long),null);
								}
								catch
								{
									throw new ArgumentException("value is a name, but not one of the named constants defined for the enumeration.");
								}
								//
							}
						}
					}


					//return the total converted back to the correct enum type
					return System.Enum.ToObject(enumType, returnVal);
				}
				else
				{
					//the type supplied does not derive from enum
					throw new ArgumentException("enumType parameter is not an System.Enum");
				}
			}
#endif
		}
 private static CustomProperty CreateCustomProperty(IServiceProvider serviceProvider, System.Type customActivityType, MemberInfo member, System.Type propertyType)
 {
     CustomProperty property = new CustomProperty(serviceProvider) {
         Name = member.Name,
         IsEvent = member is EventInfo
     };
     if (propertyType == typeof(ActivityBind))
     {
         property.GenerateDependencyProperty = false;
         property.Type = typeof(ActivityBind).FullName;
     }
     else
     {
         FieldInfo field = customActivityType.GetField(member.Name + (property.IsEvent ? "Event" : "Property"), BindingFlags.Public | BindingFlags.Static);
         if ((field != null) && (field.FieldType == typeof(DependencyProperty)))
         {
             property.GenerateDependencyProperty = true;
         }
         else
         {
             property.GenerateDependencyProperty = false;
         }
         property.Type = propertyType.FullName;
     }
     property.oldPropertyName = member.Name;
     property.oldPropertyType = propertyType.FullName;
     object[] customAttributes = member.GetCustomAttributes(typeof(FlagsAttribute), true);
     if ((customAttributes != null) && (customAttributes.Length > 0))
     {
         property.Hidden = true;
     }
     foreach (object obj2 in member.GetCustomAttributes(false))
     {
         AttributeInfoAttribute attribute = obj2 as AttributeInfoAttribute;
         AttributeInfo info2 = (attribute != null) ? attribute.AttributeInfo : null;
         if (info2 != null)
         {
             try
             {
                 if ((info2.AttributeType == typeof(BrowsableAttribute)) && (info2.ArgumentValues.Count > 0))
                 {
                     property.Browseable = (bool) info2.GetArgumentValueAs(serviceProvider, 0, typeof(bool));
                 }
                 else if ((info2.AttributeType == typeof(CategoryAttribute)) && (info2.ArgumentValues.Count > 0))
                 {
                     property.Category = info2.GetArgumentValueAs(serviceProvider, 0, typeof(string)) as string;
                 }
                 else if ((info2.AttributeType == typeof(DescriptionAttribute)) && (info2.ArgumentValues.Count > 0))
                 {
                     property.Description = info2.GetArgumentValueAs(serviceProvider, 0, typeof(string)) as string;
                 }
                 else if ((info2.AttributeType == typeof(DesignerSerializationVisibilityAttribute)) && (info2.ArgumentValues.Count > 0))
                 {
                     property.DesignerSerializationVisibility = (DesignerSerializationVisibility) info2.GetArgumentValueAs(serviceProvider, 0, typeof(DesignerSerializationVisibility));
                 }
                 else if ((info2.AttributeType == typeof(EditorAttribute)) && (info2.ArgumentValues.Count > 1))
                 {
                     System.Type type = info2.GetArgumentValueAs(serviceProvider, 1, typeof(System.Type)) as System.Type;
                     if (type == typeof(UITypeEditor))
                     {
                         System.Type type2 = info2.GetArgumentValueAs(serviceProvider, 0, typeof(System.Type)) as System.Type;
                         if (type2 != null)
                         {
                             property.UITypeEditor = type2.FullName;
                         }
                         if (string.IsNullOrEmpty(property.UITypeEditor))
                         {
                             property.UITypeEditor = info2.GetArgumentValueAs(serviceProvider, 0, typeof(string)) as string;
                         }
                     }
                 }
             }
             catch
             {
             }
         }
     }
     return property;
 }