0

假设我有一个自定义类 CustomClass,并且我有一个从名为 CustomClassCollection 的 CollectionBase 类派生的集合。假设我做了这样的事情:

CustomClassCollection a = new CustomClassCollection();
CustomClassCollection b = a;

当我更改 CustomClass 中的元素时a,中的元素b也会更改。我应该如何编写这些类,以便当我分配ab更改 的元素时ba仍然保持不变?

4

4 回答 4

6

您需要Clone(实现IClonable)或复制构造函数CustomClassCollection

于 2012-10-11T13:24:26.797 回答
1

你也可以试试MemberwiseClone();

YourType other = (YourType) YourInstance.MemberwiseClone(); 

链接:http: //msdn.microsoft.com/fr-fr/library/system.object.memberwiseclone.aspx

于 2012-10-11T13:27:18.803 回答
1

您需要在集合Clone的类型上实现方法。

在您可以在集合本身上实现方法之后,克隆集合的每个元素会将其添加到目标

于 2012-10-11T13:28:07.073 回答
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"));
于 2012-10-11T13:47:47.347 回答