2012-12-18 39 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); 
相关问题