假设我有一个自定义类CustomClass,我有一个派生自CollectionBase类的名为CustomClassCollection的集合。假设我做的是这样的事情:
CustomClassCollection a = new CustomClassCollection();
CustomClassCollection b = a;
当我更改a
中的CustomClass元素时,b
中的元素也会更改。我应该如何编写这些类,以便在我将a
分配给b
并更改b
的元素时,a
仍保持不变?
答案 0 :(得分:6)
Clone
需要IClonable
(实施CustomClassCollection
)或复制构造函数。
答案 1 :(得分:1)
您也可以尝试使用MemberwiseClone();
YourType other = (YourType) YourInstance.MemberwiseClone();
链接:http://msdn.microsoft.com/fr-fr/library/system.object.memberwiseclone.aspx
答案 2 :(得分:1)
您需要在内部集合中实施Clone
方法。
在您可以对集合本身实现方法之后,克隆 source 集合的每个元素会将其添加到 destination 。
答案 3 :(得分:0)
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
class CustomClass
{
int _id;
string _value;
public CustomClass(int id, string value)
{
_id = id;
_value = value;
}
}
[Serializable]
class CustomClassCollection
{
private IList<CustomClass> _list = null;
public CustomClassCollection()
{
_list = new List<CustomClass>();
}
public void Add(CustomClass a)
{
_list.Add(a);
}
}
public static class CloneManager
{
public static T Clone<T>(this T source)
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", "source");
}
if (Object.ReferenceEquals(source, null))
{
return default(T);
}
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
}
使用它像:
CustomClassCollection a = new CustomClassCollection();
CustomClassCollection b = ObjectCopier.Clone<CustomClassCollection>(a);
a.Add(new CustomClass(1, "A"));
a.Add(new CustomClass(2, "B"));
a.Add(new CustomClass(3, "C"));
b.Add(new CustomClass(1, "A"));
b.Add(new CustomClass(2, "B"));