按C#中的值复制Collection元素



在下面的代码中,添加了一个引用类型。如何进行此值类型?

 imgList.Items.Add(imgList.Items[0]);
    imgList.Items[imgIndex].Data = input; <== **This updates the 0th and the newly added element which is the issues**

请告知

为了避免此问题,需要先克隆imgList.Items[0],然后再将其添加到imgList.Items。这基本上包括创建一个相同类型的新对象,并用原始对象中的数据填充它。

这样做的复杂性取决于对象是什么,但请查看此问题的答案,了解有关克隆对象的一些提示。

编辑:我忘了。MemberwiseClone受到保护。

您不会在代码中说明要添加到列表中的对象的类型。如果它是你的一个类,你可以添加一个方法来返回副本:

public MyType ShallowCopy()
{
    return (MyType)this.MemberwiseClone();
}

并使用

imgList.Items.Add(imgList.Items[0].ShallowCopy());

或者你可以添加一个复制构造函数:

public MyType(MyType original)
{
    // Copy each of the properties from original
    this.Data = original.Data;
}

并使用

imgList.Items.Add(new MyType(imgList.Items[0]));

最新更新