2011-10-14 44 views
5

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

+2

可能重复(http://stackoverflow.com/questions/2417023/clone-whole-object-graph) – xanatos

+1

快速和肮脏的解决方案是序列化对象,并立即反序列化到另一个对象。当然,这取决于对象是否可以正确序列化... – canon

回答

4

我看到这是一个解决方案,基本上都是写自己的函数来做到这一点,因为你说的关于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); 
    } 
} 

我引用这个线程什么。 copy a class, C#

0
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); 
} 

OR

if (pi.CanRead && pi.CanWrite && 
    (pi.PropertyType.IsEnum || pi.PropertyType.IsArray)) 
{ 
    ...; 
} 
[克隆所有对象图]的
+0

这是以某种方式递归的方式,我无法清楚地看到吗? –

相关问题