如何处理添加到列表事件? [英] How to handle add to list event?
问题描述
我有一个这样的列表:
List<Controls> list = new List<Controls>
如何处理向此列表添加新位置?
How to handle adding new position to this list?
当我这样做时:
myObject.myList.Add(new Control());
我想在我的对象中做这样的事情:
I would like to do something like this in my object:
myList.AddingEvent += HandleAddingEvent
然后在我的 HandleAddingEvent
委托处理中添加位置到这个列表.我应该如何处理添加新位置事件?我怎样才能使这个活动可用?
And then in my HandleAddingEvent
delegate handling adding position to this list. How should I handle adding new position event? How can I make this event available?
推荐答案
您可以从 List 继承并添加您自己的处理程序,例如
You could inherit from List and add your own handler, something like
using System;
using System.Collections.Generic;
namespace test
{
class Program
{
class MyList<T> : List<T>
{
public event EventHandler OnAdd;
public new void Add(T item) // "new" to avoid compiler-warnings, because we're hiding a method from base-class
{
if (null != OnAdd)
{
OnAdd(this, null);
}
base.Add(item);
}
}
static void Main(string[] args)
{
MyList<int> l = new MyList<int>();
l.OnAdd += new EventHandler(l_OnAdd);
l.Add(1);
}
static void l_OnAdd(object sender, EventArgs e)
{
Console.WriteLine("Element added...");
}
}
}
警告
请注意,您必须重新实现所有将对象添加到列表中的方法.
AddRange()
在这个实现中不会触发这个事件.
Be aware that you have to re-implement all methods which add objects to your list.
AddRange()
will not fire this event, in this implementation.
我们没有超载该方法.我们把原来的藏了起来.如果你Add()
一个对象,而这个类在List
中被装箱,事件将不会被触发强>!
We did not overload the method. We hid the original one. If you Add()
an object while this class is boxed in List<T>
, the event will not be fired!
MyList<int> l = new MyList<int>();
l.OnAdd += new EventHandler(l_OnAdd);
l.Add(1); // Will work
List<int> baseList = l;
baseList.Add(2); // Will NOT work!!!
这篇关于如何处理添加到列表事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!