Mono.Helper.GetConverterFor C# (CSharp) Method

GetConverterFor() public static method

public static GetConverterFor ( MemberInfo info, Type target_type ) : TypeConverter
info System.Reflection.MemberInfo
target_type System.Type
return System.ComponentModel.TypeConverter
		public static TypeConverter GetConverterFor (MemberInfo info, Type target_type)
		{
			Attribute[] attrs;
			TypeConverterAttribute at = null;
			TypeConverter converter = null;
			Type t = null;

			// first check for a TypeConverter attribute on the property
			if (info != null) {
				attrs = (Attribute[])info.GetCustomAttributes (true);
				foreach (Attribute attr in attrs) {
					if (attr is TypeConverterAttribute) {
						at = (TypeConverterAttribute)attr;
						break;
					}
				}
			}

			if (at == null) {
				// we didn't find one on the property.
				// check for one on the Type.
				attrs = (Attribute[])target_type.GetCustomAttributes (true);
				foreach (Attribute attr in attrs) {
					if (attr is TypeConverterAttribute) {
						at = (TypeConverterAttribute)attr;
						break;
					}
				}
			}

			if (at == null) {
				if (target_type == typeof (bool?)) {
					t = typeof (NullableBoolConverter);
				} else {
					return null;
				}
			} else {
				t = Type.GetType (at.ConverterTypeName);
			}

			if (t == null || !typeof (TypeConverter).IsAssignableFrom (t))
				return null;

			ConstructorInfo ci = t.GetConstructor (new Type[] { typeof(Type) });
			if (ci != null)
				converter = (TypeConverter) ci.Invoke (new object[] { target_type });
			else
				converter = (TypeConverter) Activator.CreateInstance (t);

			return converter;
		}

Usage Example

Beispiel #1
0
        public static object ConvertObject(PropertyInfo prop, object val, Type objectType)
        {
            // Should i return default(T) if property.PropertyType is a valuetype?
            if (val == null)
            {
                return(val);
            }

            if (prop.PropertyType.IsAssignableFrom(val.GetType()))
            {
                return(val);
            }

            if (prop.PropertyType == typeof(string))
            {
                return(val.ToString());
            }

            TypeConverter tc = Helper.GetConverterFor(prop, prop.PropertyType);

            if (tc == null)
            {
                tc = new MoonlightTypeConverter(prop.Name, prop.PropertyType);
            }

            return(tc.ConvertFrom(null, Helper.DefaultCulture, val));
        }
All Usage Examples Of Mono.Helper::GetConverterFor