Net Core教程

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

  

这篇关于C# 利用反射实现深拷贝的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!