c#监听List数量变化

using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using UnityEngine;
/*转为UTF-8*/
public class ObserveList : MonoBehaviour
{
    public ObservableCollection<myData> collection = new ObservableCollection<myData>();


    private void Start()
    {
        //注册事件:当数组数量发生变化时,打印数组长度
        collection.CollectionChanged += Collection_CollectionChanged;
    }

    private void Collection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        Debug.Log(((ObservableCollection<myData>)sender).Count);
        //TODO:
    }



    private void TestAddItemToList()
    {
        collection.Add(new myData(1));
    }


    private void RemoveItemFromList()
    {
        //方式1:先查找再移除(推荐用于ObservableCollection)
        collection = new ObservableCollection<myData>(collection.Where(item=>item.dataID!=1));

        //方式2:

    }

}

public class myData
{
    public int dataID;

    public myData(int id)
    {
        this.dataID = id;
    }
}
View Code

 

posted @ 2024-12-25 17:29  SummerTrainnn  阅读(48)  评论(0)    收藏  举报