How can I make an Observable Hashset in C#?

后端 未结 3 1534
轮回少年
轮回少年 2020-12-14 19:50

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

相关标签:
3条回答
  • 2020-12-14 20:34

    I've posted a complete ObservableHashSet here that you can use.

    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.

    0 讨论(0)
  • 2020-12-14 20:50

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-14 20:51

    You have to implement INotifyCollectionChanged too, and then it should all work OK. There's another relevant SO answer which uses freezables to ensure that changes in underlying entities are also handled.

    0 讨论(0)
提交回复
热议问题