Exemplo n.º 1
0
        public static IDictionary <string, object> Get(T obj)
        {
            var result = new Dictionary <string, object>();

            var type = typeof(T);

            var helpers = cache.GetOrAdd(type, _ =>
            {
                var allProperties = type.GetTypeInfo().DeclaredProperties;

                var listOfHelpers = new List <ReflectionPropertyHelper <T> >();

                foreach (var property in allProperties)
                {
                    // MyClass.Integer
                    var getMethod = property.GetMethod;
                    var input     = getMethod.DeclaringType; // MyClass
                    var output    = getMethod.ReturnType;    // int

                    // Func<MyClass, int>
                    var openGenericType = typeOfOpenFunc.MakeGenericType(input, output);
                    var getterDelegate  = getMethod.CreateDelegate(openGenericType);

                    var wrapperDelegate = callPropertyMethod.MakeGenericMethod(
                        input, output);

                    var specificDelegate = (Func <T, object>)
                                           wrapperDelegate.CreateDelegate(closedGenericFunc, getterDelegate);

                    var propertyHelper = new ReflectionPropertyHelper <T>
                    {
                        Name   = property.Name,
                        Getter = specificDelegate
                    };

                    listOfHelpers.Add(propertyHelper);
                }

                return(listOfHelpers);
            });

            foreach (var helper in helpers)
            {
                result.Add(helper.Name, helper.Getter(obj));
            }

            return(result);
        }
Exemplo n.º 2
0
 public static IDictionary <string, object> ToDictionary <T>(this T obj)
 {
     return(ReflectionPropertyHelper <T> .Get(obj));
 }