编程语言
首页 > 编程语言> > C# 利用反射实现深拷贝

C# 利用反射实现深拷贝

作者:互联网

//利用反射实现深拷贝
        public static T DeepCopyByReflection<T>(this T tSource)
        {
            T tResult = Activator.CreateInstance<T>();
            Type sourceType = typeof(T);
            Type resultType = typeof(T);
            var sourcePros = sourceType.GetProperties();
            foreach (var pro in sourcePros)
            {
                var sourceProValue = pro.GetValue(tSource);
                var resultPro = resultType.GetProperty(pro.Name);
                resultPro.SetValue(tResult, sourceProValue);
            }
            return tResult;
        }

  

Person p1 = new PPerson p2 = p1.DeepCopyByReflection();erson { Id = 1, Name = "wjire" };

  

标签:反射,Name,sourcePros,C#,pro,tResult,var,拷贝,Type
来源: https://www.cnblogs.com/JerryZhang320/p/15491968.html