C # listens to changes in List and Dictionary data (modification, clearing, etc.)
New keyword
//To hide an inherited member, declare it in the derived class by using the same member name, and modify it with the new keyword. For example: public class BaseC { public int x; public void Invoke() { } } public class DerivedC : BaseC { new public void Invoke() { } }
Listen to List
Method 1: new modifier
namespace MyObservable { #Regional public entrustment (by visiting blogs) public delegate void VoidValueCallback(); public delegate void OneValueCallback<T>(T data); public delegate void TwoValueCallback<T1, T2>(T1 data1, T2 data2); #endregion public class ObserveList<T> : System.Collections.Generic.List<T> { public VoidValueCallback DOnClear; public OneValueCallback<T> DOnAdd, DOnRemove; public OneValueCallback<System.Collections.Generic.IEnumerable<T>> DOnAddRange; #Rewriting the region construction method (www.azimiao. com) public ObserveList():base() { } public ObserveList(System. Collections.Generic.IEnumerable<T> collection) : base(collection) { } public ObserveList(int num) : base(num) { } #endregion /// <summary> ///Note that removeall is not clear, and its call parameters are matching rules /// </summary> public OneValueCallback<int> DOnRemoveAll; public OneValueCallback<int> DOnRemoveAt; public TwoValueCallback<int, int> DOnRemoveRange; public new void Add(T item) { base.Add(item); DOnAdd?.Invoke(item); } public new void AddRange(System. Collections.Generic.IEnumerable<T> collection) { base.AddRange(collection); DOnAddRange?.Invoke(collection); } public new bool Remove(T item) { bool flag = base.Remove(item); if (flag) { DOnRemove?.Invoke(item); } return flag; } public new void Clear() { base.Clear(); DOnClear?.Invoke(); } public new int RemoveAll(Predicate<T> match) { int num = base.RemoveAll(match); DOnRemoveAll?.Invoke(num); return num; } public new void RemoveAt(int index) { base.RemoveAt(index); DOnRemoveAt?.Invoke(index); } public new void RemoveRange(int index, int count) { base.RemoveRange(index, count); DOnRemoveRange?.Invoke(index, count); } } }
class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); MyObservable.ObserveList<int> test1 = new MyObservable.ObserveList<int>(0); test1.DOnAdd += (int a) => { Console.WriteLine("add a number:" + a); }; test1.DOnRemove += (int a) => { Console.WriteLine("delete a number:" + a); }; test1.DOnClear += () =>{ Console.WriteLine("clear~"); }; test1.Add(100); test1.Remove(100); test1.Clear(); Console.ReadKey(); } }
Hello World! add a number:100 delete a number:100 clear~
Method 2: Implement the IList<T>interface
Monitor Dictionary
Method 1: new modifier
Method 2: Implement the IDictionary<T>interface
https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.idictionary-2