Esempio n. 1
0
        // Safe null values method
        public static T GetValue <T>(this object obj, string propertyName) // where T : IConvertible
        {
            if (obj == null)
            {
                return(default(T));
            }

            if (obj is ExpandoObject || obj is IDictionary <string, object> )
            {
                var    dict  = obj as IDictionary <string, object>;
                object value = null;
                dict.TryGetValue(propertyName, out value);
                return((T)value);
            }

            PropertyDescriptor pi = ReflectionCache.GetProperty(obj, propertyName);

            if (pi == null)    //  || !pi.CanRead // .CanWrite
            {
                return(default(T));
            }

            object valueProp = obj.GetPropertyValue(propertyName);

            if (valueProp == null)
            {
                return(default(T));
            }

            var type = typeof(T);

            if (type.IsValueType)
            {
                var nullType = Nullable.GetUnderlyingType(type);
                if (nullType != null)
                {
                    return((T)System.Convert.ChangeType(valueProp, nullType));
                }
            }
            else
            if (valueProp.GetType().IsValueType)
            {
                return((T)System.Convert.ChangeType(valueProp, type));
            }
            else if (type.IsClass)
            {
                return((T)valueProp);
            }

            return((T)System.Convert.ChangeType(valueProp, pi.PropertyType));
        }
Esempio n. 2
0
 public static IEnumerable <PropertyDescriptor> Properties(this object obj)
 {
     return(ReflectionCache.GetProperties(obj));
 }
Esempio n. 3
0
        public static PropertyDescriptor GetPropertyDesc(object obj, string propertyName)
        {
            IEnumerable <PropertyDescriptor> prop = ReflectionCache.GetProperties(obj);

            return(Enumerable.Where(prop, (el) => el.Name == propertyName).First());
        }