复制 ObservableCollection 项目
我想复制可观察集合中的列表项。当我这样做时:
TreasureCards[TreasureCards.Count - 1] = TreasureCards[CardPosition];
它会创建特定列表项的副本,但随后它们会链接到我的 UI 中。因此,如果我更改新的重复项目的名称,它就会更改原始名称。我知道我可以一一执行每个属性(见下文),但是有没有办法复制整个项目?
TreasureCards[TreasureCards.Count - 1].Name = TreasurecCards[CardPosition].Name;
TreasureCards[TreasureCards.Count - 1].Type= TreasurecCards[CardPosition].Type;
// etc
I want to duplicate a list item in an observablecollection. When I do:
TreasureCards[TreasureCards.Count - 1] = TreasureCards[CardPosition];
It creates a copy of the specific list item but then they are linked in my UI. So if I change the new duplicated item's name, it changes the originals name. I know I could do each of the properties one by one (see below) but is there a way to just copy the entire item?
TreasureCards[TreasureCards.Count - 1].Name = TreasurecCards[CardPosition].Name;
TreasureCards[TreasureCards.Count - 1].Type= TreasurecCards[CardPosition].Type;
// etc
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您没有复制该对象。您正在创建对该对象的新引用。仍然只有一个对象;现在您的集合中有两个对它的引用,并且对对象的任何更改都会由两个引用反映出来。
要创建新对象,您可以对从
Object
派生的任何对象调用MemberwiseClone()
。此方法返回一个新实例,复制原始对象中所有字段的值。所以你会这样做:此方法有两个限制。首先,它是浅复制,即原始对象中的任何引用字段的值都会被复制。因此,如果
a.Foo
是对Bar
对象的引用,则a.MemberwiseClone().Foo
将引用同一个Bar对象。其次,该方法只是复制字段;它不会调用新对象的构造函数。根据类的设计,这要么不重要,要么非常重要。
通常,让类实现
ICloneable
并显式实现Clone()
方法会更安全,例如:You aren't duplicating the object. You're creating a new reference to the object. There's still only one object; now there are two references to it in your collection, and any change to the object is reflected by both references.
To create a new object, you can call
MemberwiseClone()
on anything that derives fromObject
. This method returns a new instance, copying the values from all fields in the original object. So you'd do:There are two limitations with this method. First, it's a shallow copy, i.e. any reference fields in the original object have their values copied. So if
a.Foo
is a reference to aBar
object,a.MemberwiseClone().Foo
will refer to the sameBar
object. Second, the method just copies the fields; it doesn't call the new object's constructor. Depending on the design of the class, this is either unimportant or a Really Big Deal.Usually, it's safer to make the class implement
ICloneable
and explicitly implement aClone()
method, e.g.:它们没有链接,它们是同一个实例。您所做的就是将对相同数据的引用复制到数组中的另一个位置。
您需要做的是实现一些 Clone 方法,该方法可以复制原始实例,但作为另一个实例。这篇帖子可能会有所帮助。
然后你会做这样的事情:
They aren't linked, they are the same instance. All you're doing is copying a reference to the same data to another position in the array.
What you need to do is implement some Clone method that makes a copy of the original instance but as another instance. This SO post might help.
Then you would do something like this: