Пример #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 (type.IsClass)
            {
                return((T)valueProp);
            }

            return((T)System.Convert.ChangeType(valueProp, pi.PropertyType));
        }
Пример #2
0
 public static IEnumerable <PropertyDescriptor> Properties(this object obj)
 {
     return(ReflectionCache.GetProperties(obj));
 }