2017-02-22 77 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