事件动作<> vs事件EventHandler<>

编程入门 行业动态 更新时间:2024-10-27 20:32:44
本文介绍了事件动作<> vs事件EventHandler<>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

声明 event Action<> 和 event EventHandler<> 有什么区别。

假定实际引发事件的对象并不重要。

Assuming it doesn't matter what object actually raised an event.

例如:

public event Action<bool, int, Blah> DiagnosticsEvent;

vs

public event EventHandler<DiagnosticsArgs> DiagnosticsEvent; class DiagnosticsArgs : EventArgs { public DiagnosticsArgs(bool b, int i, Blah bl) {...} ... }

两种情况下的用法几乎相同:

usage would be almost the same in both cases:

obj.DiagnosticsEvent += HandleDiagnosticsEvent;

关于 event EventHandler<<>有几件事我不喜欢; 模式:

  • 从 EventArgs派生的额外类型声明
  • 强制传递对象源– 通常无人问津

更多代码意味着需要维护更多代码,而无需任何明确说明优势。

More code means more code to maintain without any clear advantage.

因此,我更喜欢 event Action<>

但是,仅当Action<>中的类型参数太多时,才需要额外的类。

However, only if there are too many type arguments in Action<>, then an extra class would be required.

推荐答案

主要区别在于,如果您使用 Action<> ,则您的事件将不会遵循系统中几乎任何其他事件的设计模式考虑一个缺点。

The main difference will be that if you use Action<> your event will not follow the design pattern of virtually any other event in the system, which I would consider a drawback.

具有主导设计模式(除了相同的功能之外)的一个好处是,您可以扩展 EventArgs 具有新属性的对象,而不会更改事件的签名。如果您使用 Action< SomeClassWithProperties> 仍然可以实现,但是在那种情况下不使用常规方法并不真正有意义。

One upside with the dominating design pattern (apart from the power of sameness) is that you can extend the EventArgs object with new properties without altering the signature of the event. This would still be possible if you used Action<SomeClassWithProperties>, but I don't really see the point with not using the regular approach in that case.

更多推荐

事件动作&lt;&gt; vs事件EventHandler&lt;&gt;

本文发布于:2023-11-07 06:57:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565825.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:事件   动作   amp   EventHandler   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!