我引用的是关于弱事件的 MSDN 教程。我了解基本知识。我正在从事一个非 WPF 项目,我的类(class)正在公开某些事件。我的问题是弱事件 完全取代旧的事件模式?每个暴露事件的类都使用它好吗?大量使用弱事件有什么副作用?
最佳答案
根据我所做的阅读,使用 WeakEvents 似乎没有任何具体的负面影响,除了这样做更冗长这一事实。此外,在大多数情况下,您应该能够在不再需要事件时手动注销事件。在某些情况下,这是不可能的。例如,您引用的 MSDN 页面提到了何时应该使用 WeakEvents:
http://msdn.microsoft.com/en-us/library/aa970850.aspx
Certain scenarios inherently lend themselves to the application of the weak event pattern. One such scenario is data binding. In data binding, it is common for the source object to be completely independent of the listener object, which is a target of a binding. Many aspects of WPF data binding already have the weak event pattern applied in how the events are implemented.
唯一对他们提出任何类型的负面评价的人是这个博客:
There are a few downsides about using a weak event listeners in general:
- It’s notation is ugly, the “original” .NET way looks way better
- You have to name the event by string, that sucks (if you know a better way, contact me!)
- It can only handle events with a handler of EventHandler
- You become a lazy developer not caring about subscriptions
从本质上讲,它们应该用于您的对象将在其整个存在期间订阅的事件,并且仅在对象被释放时断开连接。对于其他一切,首选使用传统事件并手动注册/注销事件。
关于c# - 什么时候使用弱事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13788787/