示例#1
0
        public static T FromDynamic <T>(this IDictionary <string, object> dictionary)
        {
            var bindings = new List <MemberBinding>();
            var stringConverterHelper = new StringConverterHelper();

            foreach (var sourceProperty in typeof(T).GetProperties().Where(x => x.CanWrite))
            {
                var key = dictionary.Keys.SingleOrDefault(x => x.Equals(sourceProperty.Name, StringComparison.OrdinalIgnoreCase));
                if (string.IsNullOrEmpty(key))
                {
                    continue;
                }
                dynamic propertyValue = dictionary[key];

                MethodInfo method = stringConverterHelper.GetType().GetMethod("GetTfromString");
                method = method.MakeGenericMethod(sourceProperty.PropertyType);
                var value = method.Invoke(stringConverterHelper, new object[] { propertyValue.RawValue });

                bindings.Add(Expression.Bind(sourceProperty, Expression.Constant(value)));
            }
            Expression memberInit = Expression.MemberInit(Expression.New(typeof(T)), bindings);

            return(Expression.Lambda <Func <T> >(memberInit).Compile().Invoke());
        }