Пример #1
0
        public static T MapTo <T>(object obj) where T : new()
        {
            T res = new T();
            Dictionary <string, PropertyInfo> OutProps = new Dictionary <string, PropertyInfo>();

            foreach (var property in typeof(T).GetProperties())
            {
                if (property.CanRead)
                {
                    OutProps.Add(property.Name, property);
                }
            }
            foreach (var InProp in obj.GetType().GetProperties())
            {
                PropertyInfo OutProp;
                if (InProp.CanRead && OutProps.TryGetValue(InProp.Name, out OutProp))
                {
                    OutProp.SetValue(res, InProp.GetValue(obj));
                }
            }
            return(res);
        }
Пример #2
0
        public static object MapTo(Type T, object obj)
        {
            if (obj == null)
            {
                return(null);
            }
            object res = Activator.CreateInstance(T);
            Dictionary <string, PropertyInfo> OutProps = new Dictionary <string, PropertyInfo>();

            foreach (var property in T.GetProperties())
            {
                bool Ignore = (from attrib in property.CustomAttributes
                               where attrib.AttributeType == typeof(IgnoreInHelpers)
                               select attrib).Any();
                if (!Ignore && property.CanWrite)
                {
                    OutProps.Add(property.Name, property);
                }
            }

            foreach (var InProp in obj.GetType().GetProperties())
            {
                bool Ignore = (from attrib in InProp.CustomAttributes
                               where attrib.AttributeType == typeof(IgnoreInHelpers)
                               select attrib).Any();
                if (!Ignore && InProp.CanRead && OutProps.TryGetValue(InProp.Name, out PropertyInfo OutProp))
                {
                    if (OutProp.PropertyType == InProp.PropertyType)
                    {
                        OutProp.SetValue(res, InProp.GetValue(obj));
                    }
                }
            }

            return(res);
        }