事件动作<> vs事件EventHandler<> [英] event Action<> vs event EventHandler<>

查看:77
本文介绍了事件动作<> 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;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆