Csharp/C#教程:如何在没有任何引用的情况下创建类对象的副本?分享


如何在没有任何引用的情况下创建类对象的副本?

如何在没有任何引用的情况下创建类对象的副本? ICloneable制作类对象的副本(通过浅拷贝),但不支持深度复制。 我正在寻找一个足够智能的函数来读取类对象的所有成员,并在不指定成员名称的情况下对另一个对象进行深层复制。

我已经看到这是一个解决方案,基本上编写自己的函数来执行此操作,因为你所说的ICloneable没有做深度复制

 public static T DeepCopy(T other) { using (MemoryStream ms = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, other); ms.Position = 0; return (T)formatter.Deserialize(ms); } } 

我正在引用这个post。 复制一个类,C#

 public static object Clone(object obj) { object new_obj = Activator.CreateInstance(obj.GetType()); foreach (PropertyInfo pi in obj.GetType().GetProperties()) { if (pi.CanRead && pi.CanWrite && pi.PropertyType.IsSerializable) { pi.SetValue(new_obj, pi.GetValue(obj, null), null); } } return new_obj; } 

您可以根据自己的需要进行调整 例如,

 if (pi.CanRead && pi.CanWrite && (pi.PropertyType == typeof(string) || pi.PropertyType == typeof(int) || pi.PropertyType == typeof(bool)) ) { pi.SetValue(new_obj, pi.GetValue(obj, null), null); } 

要么

上述就是C#学习教程:如何在没有任何引用的情况下创建类对象的副本?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 if (pi.CanRead && pi.CanWrite && (pi.PropertyType.IsEnum || pi.PropertyType.IsArray)) { ...; } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/986637.html

(0)
上一篇 2021年12月22日
下一篇 2021年12月22日

精彩推荐