两个具有相同属性的类赋值

今天项目中有两个类,其中相同的属性比较多,手动代码量大。借鉴此篇博客https://www.cnblogs.com/gester/p/5816643.html,然后根据自身需求修改了一下,代码如下:

  [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var b = new B
            {
                Age = 1,
                UserName = "1"
            };

            var a = new A
            {
                Age = 2,
                UserName = "2",
                Sex = 2
            };

            var b2 = Mapper<B, A>(b,a);
        }

        public class A
        {
            public int Age { get; set; }
            public string UserName { get; set; }
            public int Sex { get; set; }
        }

        public class B
        {
            public int Age { get; set; }
            public string UserName { get; set; }
        }

        public static D Mapper<D, S>(D d,S s)
        {
            try
            {
                var sType = s.GetType();
                var dType = typeof(D);

                foreach (PropertyInfo sP in sType.GetProperties())
                {
                    foreach (PropertyInfo dP in dType.GetProperties())
                    {
                        if (dP.Name == sP.Name)
                        {
                            dP.SetValue(d, sP.GetValue(s)); break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }
            return d;
        }
    }

我这里两个类都是已存在的实例,这个方法是两个实例类互转。

原文地址:https://www.cnblogs.com/xiangweisareas/p/13183099.html