usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;publicclassObservableList<T>:List<T>{// Event to notify when the list changespubliceventAction OnListChanged;publiceventAction<T> OnItemChanged;publicnewvoidAdd(T item){base.Add(item);NotifyListChanged();}publicnewvoidRemove(T item){base.Remove(item);NotifyListChanged();}// Add other list modification methods as neededprivatevoidNotifyListChanged(){
OnListChanged?.Invoke();}publicvoidAddRange(IEnumerable<T> collection){base.AddRange(collection);NotifyListChanged();}publicvoidRemoveRange(IEnumerable<T> collection){base.RemoveAll(item => collection.Contains(item));NotifyListChanged();}publicnewvoidClear(){base.Clear();NotifyListChanged();}publicvoidModifyItemAt(int index,T newItem){base[index]= newItem;NotifyListChanged();}protectedvirtualvoidNotifyItemChanged(T item){
OnItemChanged?.Invoke(item);}}
在此示例中,ObservableList 类继承自 List 并包含 OnListChanged 事件。添加和删除等方法已被重写,以在修改列表后调用 NotifyListChanged。然后调用该事件来通知所有订阅的方法有关更改的信息。
这就是我们使用它的方式:
publicclassExample:MonoBehaviour{ObservableList<int> myList =newObservableList<int>();privatevoidOnEnable(){
myList.OnListChanged += HandleListChanged;}privatevoidOnDisable(){
myList.OnListChanged -= HandleListChanged;}privatevoidStart(){ChangeList();}privatevoidChangeList(){
myList.Add(42);// This will trigger HandleListChanged}privatevoidHandleListChanged(){// Do something when the list changes
Debug.Log("List changed!");}}
这是一个基本示例,您可以根据您的具体需求进一步自定义。
2.可观察字典:
我们首先关注 Observable Dictionary,看看当数据发生变化时它们如何通知我们。
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;publicclassDictionaryObservable<TKey, TValue>:Dictionary<TKey, TValue>{// Event to notify when the dictionary changespubliceventAction OnDictionaryChanged;publicnewvoidAdd(TKey key,TValuevalue){base.Add(key,value);NotifyDictionaryChanged();}publicnewboolRemove(TKey key){bool removed =base.Remove(key);if(removed)NotifyDictionaryChanged();return removed;}// Add other dictionary modification methods as neededprivatevoidNotifyDictionaryChanged(){
OnDictionaryChanged?.Invoke();}}
这是如何使用它:
publicclassExample:MonoBehaviour{DictionaryObservable<string,int> myDictionary =newDictionaryObservable<string,int>();privatevoidOnEnable(){
myDictionary.OnDictionaryChanged += HandleDictionaryChanged;}privatevoidOnDisable(){
myDictionary.OnDictionaryChanged -= HandleDictionaryChanged;}privatevoidStart(){ChangeDict();}privatevoidChangeDict(){
myDictionary.Add("One",1);// This will trigger HandleDictionaryChanged}privatevoidHandleDictionaryChanged(){// Do something when the dictionary changes
Debug.Log("Dictionary changed!");}}