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 @   SummerTrainnn  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示