Asp.net 在C中按值复制集合元素#
在下面的代码中,正在添加引用类型。我怎样做这个值类型Asp.net 在C中按值复制集合元素#,asp.net,c#-4.0,Asp.net,C# 4.0,在下面的代码中,正在添加引用类型。我怎样做这个值类型 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.Add(imgList.Items[0]); imgList.Items[imgIndex]。
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.Add(imgList.Items[0]);
imgList.Items[imgIndex]。数据=输入 为了避免此问题,您需要先克隆imgList.Items[0]
,然后再将其添加到imgList.Items
。这基本上涉及到创建一个相同类型的新对象,并用原始对象中的数据填充它
这样做的复杂性取决于对象是什么,但请查看的答案,以了解有关克隆对象的一些提示
编辑:我忘了。MemberwiseClone受到保护
您的代码中没有说明要添加到列表中的对象的类型。如果它是您的类,您可以添加一个方法来返回副本:
public MyType ShallowCopy()
{
return (MyType)this.MemberwiseClone();
}
和使用
imgList.Items.Add(imgList.Items[0].ShallowCopy());
imgList.Items.Add(new MyType(imgList.Items[0]));
或者,您可以添加副本构造函数:
public MyType(MyType original)
{
// Copy each of the properties from original
this.Data = original.Data;
}
和使用
imgList.Items.Add(imgList.Items[0].ShallowCopy());
imgList.Items.Add(new MyType(imgList.Items[0]));
MemberwiseClone(),这是内置函数吗?是,但它受保护。继承对象以覆盖它将是我的方法。