简体   繁体   English

如何在C#中创建一个Observable Hashset?

[英]How can I make an Observable Hashset in C#?

Currently I am using an ObservableCollection within a WPF application, the application is an implementation of Conway's Game of life and works well for about 500 cells but after that it begins to slow down significantly. 目前我在WPF应用程序中使用ObservableCollection,该应用程序是Conway生命游戏的一个实现,适用于大约500个单元格,但之后它开始显着减速。 I originally wrote the application using a HashSet but couldn't find any way to bind the cells to a canvas. 我最初使用HashSet编写应用程序但无法找到将单元格绑定到画布的任何方法。

Is there a way to get my HashSet to notify its binding object of changes? 有没有办法让我的HashSet通知其绑定对象的更改? My Cell class is a simple integer X,Y pair, if the pair exists the cell is alive otherwise dead. 我的Cell类是一个简单的整数X,Y对,如果该对存在,则该单元处于活着状态,否则死亡。 The Cell implements INotifyPropertyChanged and overrides GetHashCode and Equals. Cell实现了INotifyPropertyChanged并覆盖了GetHashCode和Equals。 I couldn't get the cell to display any changes, just the cells present immediately after loading. 我无法让细胞显示任何变化,只是加载后立即出现的细胞。 Is there any way to Bind a Hashset to items on a Canvas? 有没有办法将Hashset绑定到Canvas上的项目?

I don't know if this will help, but here's a really simple implementation of an "observable set" that I made for a personal project. 我不知道这是否会有所帮助,但这是我为个人项目制作的“可观察集”的一个非常简单的实现。 It essentially guards against inserting (or overwriting with) an item that is already in the collection. 它基本上防止插入(或覆盖)已经在集合中的项目。

If you wanted to you could simply return out of the methods rather than throwing an exception. 如果你想,你可以简单地退出方法而不是抛出异常。

public class SetCollection<T> : ObservableCollection<T> 
{
    protected override void InsertItem(int index, T item)
    {
        if (Contains(item)) throw new ItemExistsException(item);

        base.InsertItem(index, item);
    }

    protected override void SetItem(int index, T item)
    {
        int i = IndexOf(item);
        if (i >= 0 && i != index) throw new ItemExistsException(item);

        base.SetItem(index, item);
    }
}

You have to implement INotifyCollectionChanged too, and then it should all work OK. 您还必须实现INotifyCollectionChanged ,然后它应该都可以正常工作。 There's another relevant SO answer which uses freezables to ensure that changes in underlying entities are also handled. 还有另一个相关的SO答案,它使用freezables来确保底层实体的更改也得到处理。

I've posted a complete ObservableHashSet here that you can use. 我在这里发布了一个完整的ObservableHashSet,您可以使用它。

https://github.com/BellaCode/Public/tree/master/ObservableHashSet https://github.com/BellaCode/Public/tree/master/ObservableHashSet

It is based of reflecting on how ObservableCollection is implemented and provides the same thread-safety re-entrancy checks. 它基于如何实现ObservableCollection并提供相同的线程安全重入检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM