将S类型转换为S类型,相同属性赋值

来源:互联网 发布:30岁转行学编程 编辑:程序博客网 时间:2024/06/09 22:43

在调用接口的时候,发现二个类型的属性几乎全部相同,并且属性很多,现在需要将一个类型转换为另一个类型,并将相同属性赋值给另一个,一个个去写,浪费时间,需要抽象出一个函数,用到反射,记录一下。

        public D Mapper<D, S>(S s)        {            D d = Activator.CreateInstance<D>();            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, null), null);                        }                    }                }            }            catch (Exception ex) { } return d;        }
0 0