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" };

  

posted @ 2021-11-01 08:55  zq爱生活爱代码  阅读(141)  评论(0编辑  收藏  举报