如何复制可观察集合

发布于 2024-10-02 08:48:55 字数 176 浏览 9 评论 0原文

在这种情况下,我

Observablecollection<A> aRef = new Observablecollection<A>();
bRef = aRef(); 

都指向相同的 ObservableCollection。如何制作不同的副本?

I have

Observablecollection<A> aRef = new Observablecollection<A>();
bRef = aRef(); 

In this case both point to same ObservableCollection. How do I make a different copy?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最好是你 2024-10-09 08:48:55

这样做:

// aRef being an Observablecollection 
Observablecollection<Entity> bRef = new Observablecollection<Entity>(aRef);

这将创建一个可观察的集合,但项目仍然指向原始项目。如果您需要项目指向克隆而不是原始项目,则需要实现然后调用克隆方法。

更新

如果您尝试添加到列表,然后可观察集合具有原始列表,只需通过传递原始列表来创建可观察集合:

List<Entity> originalEnityList = GetThatOriginalEnityListFromSomewhere();
Observablecollection<Entity> bRef = new Observablecollection<Entity>(originalEnityList);

Do this:

// aRef being an Observablecollection 
Observablecollection<Entity> bRef = new Observablecollection<Entity>(aRef);

This will create an observable collection but the items are still pointing to the original items. If you need the items to point a clone rather than the original items, you need to implement and then call a cloning method.

UPDATE

If you try to add to a list and then the observable collection have the original list, just create the Observablecollection by passing the original list:

List<Entity> originalEnityList = GetThatOriginalEnityListFromSomewhere();
Observablecollection<Entity> bRef = new Observablecollection<Entity>(originalEnityList);
反差帅 2024-10-09 08:48:55

您可以在实体定义中实现 ICloneable 接口,然后使用内部强制转换创建 ObservableCollection 的副本。因此,您将拥有一个克隆的 List,而不会引用旧项目。然后,您可以使用克隆的 List 创建新的 ObservableCollection

public class YourEntity : ICloneable {
    public AnyType Property { get; set; }
    ....
    public object Clone()
    {
        return MemberwiseClone();
    }
}

实现将是

var clonedList = originalObservableCollection.Select(objEntity => (YourEntity) objEntity.Clone()).ToList();

ObservableCollection<YourEntity> clonedCollection = new ObservableCollection<YourEntity>(clonedList);

You could implement ICloneable interface in you entity definition and then make a copy of the ObservableCollection with a internal cast. As a result you will have a cloned List without any reference to old items. Then you could create your new ObservableCollection whit the cloned List

public class YourEntity : ICloneable {
    public AnyType Property { get; set; }
    ....
    public object Clone()
    {
        return MemberwiseClone();
    }
}

The implementation would be

var clonedList = originalObservableCollection.Select(objEntity => (YourEntity) objEntity.Clone()).ToList();

ObservableCollection<YourEntity> clonedCollection = new ObservableCollection<YourEntity>(clonedList);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文