Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我在博客中读到(现在不记得了),建议在定义许多事件时使用属性语法(添加、删除块),而这些事件中的任何一个都应该在任何时候处理。在其他条件下使用字段语法很好。
这是什么原因?
如果通过“属性语法”你的意思是覆盖添加/删除即
public event EventHandler MyEvent { add { ... } remove { ... } }
那么只有当您想更改特定事件的添加/删除行为时,您才会这样做,即当您在事件上调用+=/时会发生什么-=。
+=
-=
对于事件的一般用途,您几乎总是使用字段声明,即
public event EventHandler MyEvent;