开发者

copy a Collection element by value in C#

In the code below,开发者_如何学JAVA a reference type is being added. How can i do this value type?

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

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

Please advise


In order to avoid this issue, you need to clone imgList.Items[0] before adding it to imgList.Items. This basically involves creating a new object of the same type and populating it with data from the original.

The complexity of doing so depends on what the object is, but look at the answers to this question for some tips on cloning objects.

Edit: I forgot that .MemberwiseClone was protected.

You don't say in your code what the type of object is that you're adding to the list. If it's a class of yours, you can add a method to return a copy:

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

and use

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

Or you can add a copy constructor:

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

and use

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜