当你的才华不能撑起你的野心时,就是你该选择学习的时候了!

C#利用反射和泛型给不同对象赋值

/// <summary>
        /// 适用于初始化新实体
        /// </summary>
        static public T RotationMapping<T, S>(S s)
        {
            T target = Activator.CreateInstance<T>();
            var originalObj = s.GetType();
            var targetObj = typeof(T);
            foreach (PropertyInfo original in originalObj.GetProperties())
            {
                foreach (PropertyInfo t in targetObj.GetProperties())
                {
                    if (t.Name == original.Name)
                    {
                        t.SetValue(target, original.GetValue(s, null), null);
                    }
                }
            }
            return target;
        }
        /// <summary>
        /// 适用于没有新建实体之间
        /// </summary>
        static public T RotationMapping<T, S>(T t, S s)
        {
            var originalObj = s.GetType();
            var targetObj = typeof(T);
            foreach (PropertyInfo sp in originalObj.GetProperties())
            {
                foreach (PropertyInfo dp in targetObj.GetProperties())
                {
                    if (dp.Name == sp.Name)
                    {
                        dp.SetValue(t, sp.GetValue(s, null), null);
                    }
                }
            }
            return t;
        }

 

posted @ 2019-10-25 14:34  hofmann  阅读(1658)  评论(0编辑  收藏  举报