c# - 如何实现事件

标签 c# events collections

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/

相关文章:

c# - http 模块 : Request is not available

c# - 为什么我的对象不为空

c# - 如何在 C# 中创建 xAPI (Tin Can) LRS (Learning Record Store)

c# - 是否可以编写一个类来隐藏添加 WeakEventManager 处理程序和传统处理程序之间的区别?

javascript - Jquery 后期绑定(bind)使用 on - 旧表单不起作用?

python - PyGame 自定义事件

java - 如何使用java将列表中的Employee对象转换为student对象?

c# - LINQ to XML 递归查询

java - 如何在无空设计中实现List、Set、Map?

java - 如何在java中的任何二维数组中存储不同数据类型的多个字段?