2012-12-18 37 views
2

我試圖在自定義數據結構上執行深層複製。我的問題是保存我想要複製的數據的數組(object[])有許多不同類型(string,System.DateTime,自定義結構等)。執行下面的循環會複製一個對象的引用,所以在一個對象中所做的任何更改都會反映在另一個對象中。從未知類型的數組中創建對象的新實例

for (int i = 0; i < oldItems.Length; ++i) 
{ 
    newItems[i] = oldItems[i]; 
} 

是否有一種通用的方法來創建這些對象的新實例,然後將任何值複製到它們中?

P.s.必須避免第三方庫

+0

序列化是否足夠? –

回答

0

假設Automapper是出了問題(如@lazyberezovsky在他的回答說明),可以序列它副本:

public object[] Copy(object obj) { 
    using (var memoryStream = new MemoryStream()) { 
     BinaryFormatter formatter = new BinaryFormatter(); 
     formatter.Serialize(memoryStream, obj); 
     memoryStream.Position = 0; 

     return (object[])formatter.Deserialize(memoryStream); 
    } 
} 

[Serializable] 
class testobj { 
    public string Name { get; set; } 
} 

class Program { 
    static object[] list = new object[] { new testobj() { Name = "TEST" } }; 

    static void Main(string[] args) { 

     object[] clonedList = Copy(list); 

     (clonedList[0] as testobj).Name = "BLAH"; 

     Console.WriteLine((list[0] as testobj).Name); // prints "TEST" 
     Console.WriteLine((clonedList[0] as testobj).Name); // prints "BLAH" 
    } 
} 

但請注意:這將是非常低效的..當然有更好的方法來做你想做的事情。

2

你可以做到這一點與automapper(可從的NuGet):

object oldItem = oldItems[i]; 
Type type = oldItem.GetType(); 
Mapper.CreateMap(type, type); 
// creates new object of same type and copies all values 
newItems[i] = Mapper.Map(oldItem, type, type); 
相關問題