Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Collections.Specialized;
- using ChangedEventArgs = System.Collections.Specialized.NotifyCollectionChangedEventArgs;
- using Actions = System.Collections.Specialized.NotifyCollectionChangedAction;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- var rs = new ObservableHashSet<int>();
- for (int i = 0; i < 15; i++)
- {
- rs.Add(i);
- }
- rs.CollectionChanged += (s, e) =>
- {
- var r = e.OldItems;
- switch (e.Action)
- {
- case Actions.Add: Console.WriteLine(e.NewItems[0]); break;
- case Actions.Remove: Console.WriteLine(e.OldItems[0]); break;
- case Actions.Reset: Console.WriteLine("rm"); break;
- }
- };
- rs.Add(18);
- rs.Remove(18);
- rs.Clear();
- Console.WriteLine(rs.Count);
- Console.Read();
- }
- }
- public class ObservableHashSet<T> : HashSet<T>, INotifyCollectionChanged
- {
- public event NotifyCollectionChangedEventHandler CollectionChanged;
- public ObservableHashSet() { }
- public ObservableHashSet(IEnumerable<T> list)
- : base(list){}
- public new bool Add(T value)
- {
- if (base.Add(value))
- {
- if (CollectionChanged != null) CollectionChanged.Invoke(this, new ChangedEventArgs(Actions.Add, value));
- return true;
- }
- return false;
- }
- public new bool Remove(T value)
- {
- if( base.Remove(value))
- {
- if (CollectionChanged != null) CollectionChanged.Invoke(this, new ChangedEventArgs(Actions.Remove, value));
- return true;
- }
- return false;
- }
- public new int Clear()
- {
- int cnt = base.Count;
- if (cnt > 0)
- {
- base.Clear();
- if (CollectionChanged != null) CollectionChanged.Invoke(this, new ChangedEventArgs(Actions.Reset, null));
- return -cnt;
- }
- return 0;
- }
- public void OnCollectionChanged(ChangedEventArgs e)
- {
- if (CollectionChanged != null) CollectionChanged.Invoke(this, e);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement