最近在做编辑器,我们创建一个物体在数据类中就被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有需要监听的也可以自己添加。如有错误,欢迎留言。