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

如何在没有任何引用的情况下创建类对象的副本? 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); } 

要么

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