2017-02-22 47 views
0

我正在使用下面的类来进行深度克隆而无序列化。使用反射对集合(键/值对)进行深度克隆

public class AbstractClone 
{ 

    public AbstractClone Clone() 
    { 
     Type typeSource = this.GetType(); 
     AbstractClone tObject = (AbstractClone)FormatterServices.GetUninitializedObject(typeSource); 

     PropertyInfo[] propertyInfo = typeSource.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); 

     foreach (PropertyInfo property in propertyInfo) 
     { 
      if (property.CanWrite) 
      { 

       if (property.PropertyType.IsValueType || property.PropertyType.IsEnum || property.PropertyType.Equals(typeof(System.String))) 
       { 
        property.SetValue(tObject, property.GetValue(this, null), null); 
       } 
       else 
       { 
        object objPropertyValue = property.GetValue(this, null); 

        if (objPropertyValue == null) 
        { 
         property.SetValue(tObject, null, null); 
        } 
        else 
        { 
         property.SetValue(tObject, ((AbstractClone)objPropertyValue).Clone(), null); 
        } 
       } 
      } 

     } 
     return tObject; 
    } 
} 

我继承了所有需要克隆的类。

这正常工作与所有对象除了键值对或集合类似排序列表,字典等

任何人都可以提出一个方法克隆键值对像字典的排序列表。

回答

0

深拷贝是一项非常重要的任务。首先,你的解决方案可能根本无法使用,因为它需要继承你的类型,并且你不能继承第三方类。第二个问题是,它并不是真正意义上深:将复制的所有引用:

class Employee 
{ 
    public string Name {get; set;} 
    public Position Position {get; set;} 
} 
class Position 
{ 
    public string Name {get;set;} 
    public int ID {get;set;} 
} 

如果在原始对象更改属性属性PositionName,你会看到在您的副本这些变化。 如果您尝试升级解决方案以递归方式运行属性,则必须处理循环引用。

但是,这项工作已经完成,您只需寻找一个现成的解决方案,例如this one