class Foo(){
public List<string> SomeCollection;
}
我需要实现一个事件,当从集合中添加或删除某些内容时可以触发该事件。如何做到这一点?
最佳答案
List<T>
没有通知支持。你可以看看BindingList<T>
,其中有事件 - 或 Collection<T>
,可以通过重写方法继承。
如果您想在 Foo
公开该事件级别,也许类似于下面的内容 - 但将其保留在列表中可能更容易:
class Foo{
public event EventHandler ListChanged;
private readonly BindingList<string> list;
public Foo() {
list = new BindingList<string>();
list.ListChanged += list_ListChanged;
}
void list_ListChanged(object sender, ListChangedEventArgs e) {
EventHandler handler = ListChanged;
if (handler != null) handler(this, EventArgs.Empty);
}
public IList<string> SomeCollection {get {return list;}}
}
关于c# - 如何实现事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1051426/