c# - 什么时候使用弱事件?

标签 c# .net mef

我引用的是关于弱事件的 MSDN 教程。我了解基本知识。我正在从事一个非 WPF 项目,我的类(class)正在公开某些事件。我的问题是弱事件 完全取代旧的事件模式?每个暴露事件的类都使用它好吗?大量使用弱事件有什么副作用?

最佳答案

根据我所做的阅读,使用 Wea​​kEvents 似乎没有任何具体的负面影响,除了这样做更冗长这一事实。此外,在大多数情况下,您应该能够在不再需要事件时手动注销事件。在某些情况下,这是不可能的。例如,您引用的 MSDN 页面提到了何时应该使用 Wea​​kEvents:

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.

唯一对他们提出任何类型的负面评价的人是这个博客:

http://blog.catenalogic.com/post/2011/11/23/A-weak-event-listener-for-WPF-Silverlight-and-Windows-Phone-7.aspx

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/

相关文章:

c# - 垃圾回收——通过强引用访问对象总是安全的吗?

.net - Asp Net Mvc 中的 SOLID 原理、Repository 模式和 EntityFramework 缓存

c# - 为什么在类中声明同名实例级静态字段时,方法作用域参数值会乱码

c# - 在 C# 中路由 API 调用返回 NotFound

c# - Umbraco 检查 Azure 上消失的索引

c# - 类型参数的约束,是否可以有可选类型

c# - 大型列表上的 plinq 需要花费大量时间

c# - Ninject 相当于 MEF AssemblyCatalog

.net - MEF ComposeParts。如何处理插件异常

asp.net - 线程安全和 MEF 目录