C# 重写List数组 监听数组变化

最近在做编辑器,我们创建一个物体在数据类中就被add到管理数组中。当增加一个线段到数组中,我们要计算线段和其他线段是否有交点等一系列问题,这时候就需要我们在数组增加和移除处重写并增加事件推送。代码如下:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class MyList<T> : List<T>
{
    /// <summary>
    /// 增加元素触发事件
    /// </summary>
    public Action<T> addAction;
    /// <summary>
    /// 移除元素触发事件
    /// </summary>
    public Action<T> removeAction;
    /// <summary>
    /// 数组改变触发事件
    /// </summary>
    public Action<T> changeAction;
    /// <summary>
    /// 清除数组触发事件
    /// </summary>
    private Action clearAction;

    public MyList()
    {

    }


    public new void Add(T item)
    {
        base.Add(item);
        if(addAction!=null) addAction.Invoke(item);
        if(changeAction!=null)changeAction.Invoke(item);
    }


    public new void Remove(T item)
    {
        base.Remove(item);
        if (removeAction != null) removeAction.Invoke(item);
        if (changeAction != null) changeAction.Invoke(item);
    }

    public new void AddRanage(IEnumerable<T> collection)
    {
        base.AddRange(collection);
        for (int i = 0; i < collection.Count(); i++)
        {
            if (addAction != null) addAction.Invoke(collection.ElementAt(i));
            if (changeAction != null) changeAction.Invoke(collection.ElementAt(i));
        }
    }


    public new void RemoveRange(int index,int count)
    {
        if (index < this.Count && index + count < this.Count)
        {
            for (int i = index; i < index+count; i++)
            {
                if (removeAction != null) removeAction.Invoke(this[i]);
                if (changeAction != null) changeAction.Invoke(this[i]);
            }
        }
        base.RemoveRange(index,count);
    }

    public new void Clear()
    {
        base.Clear();
        if(clearAction!=null)
            clearAction.Invoke();
    }
}

对于插入Insert有需要监听的也可以自己添加。如有错误,欢迎留言。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值