创建一个没有标准(Obj sender,EventArgs args)签名的事件处理程序委托有多么错误?

我理解使用标准MS事件处理程序委托签名的好处,因为它允许您轻松扩展通过事件传递的信息,而不会破坏任何基于旧委托签名的旧关系。

我想知道在实践中人们经常遵循这条规则吗? 说我有一个像这样的简单事件

public event NameChangedHandler NameChanged; public delegate void NameChangedHandler(Object sender, string oldName, string newName); 

这是一个简单的事件,我几乎肯定我从NameChanged事件中需要知道的唯一参数是名称已更改的对象,旧名称和新名称。 那么创建一个单独的NameChangedEventArgs类是否值得,或者像这样的简单事件是否可以直接通过委托参数返回参数?

如果你是唯一一个必须处理它的人,你可以采取任何错误的方式。 但是,学习标准并坚持使用这些标准并不是一个坏主意,以便在与其他人一起处理代码时保持良好的习惯。

所以我会帮你做个交易。 如果你保证以正确的方式做到这一点,我会给你一个代码片段,这样可以减轻痛苦。 只需将其放在.snippet文件中,并将该文件放入:

我的Documents \ Visual Studio 2008 \ Code Snippets \ Visual C#\ My Code Snippets \
(或Visual Studio 2005,如果适用)

这是片段; 通过输入ev2Generic并点击Tab键在VS中使用它:

    
Generic event with two types/arguments. ev2Generic Code snippet for event handler and On method Kyralessa Expansion
type1 Type of the first property in the EventArgs subclass. propertyType1 arg1Name Name of the first argument in the EventArgs subclass constructor. property1Name property1Name Name of the first property in the EventArgs subclass. Property1Name type2 Type of the second property in the EventArgs subclass. propertyType2 arg2Name Name of the second argument in the EventArgs subclass constructor. property2Name property2Name Name of the second property in the EventArgs subclass. Property2Name eventName Name of the event NameOfEvent $eventName$; protected virtual void On$eventName$($eventName$EventArgs e) { var handler = $eventName$; if (handler != null) handler(this, e); }]]>

EventHandler使用EventHandlergenerics委托,并创建从EventArgs派生的类型来保存事件数据。 换句话说,永远。 当你碰到它时,你总是知道它是如何工作的,因为它从来没有做过。

编辑:

代码分析CA1003:使用通用事件处理程序实例
代码分析CA1009:正确声明事件处理程序

在实践中,人们经常使用[不使用EventArgs派生类]。

我从未遇到过没有使用EventArgs派生类的时间。 正如您自己所说,它会提高您以后更改代码的能力。 我还认为可读性得到了改进,因为很容易看出这是一个事件处理程序。

是否值得创建一个单独的NameChangedEventArgs类,或者像这样的简单事件是否可以直接通过委托参数返回参数?

你好像说你会使用EventArgs为更多参数的事件处理程序而不是像这样的实例使用它。 老实说,在C#编程时,这根本不是一个选项。 一致性是必须的,特别是在今天这样的论坛世界中,开源项目等很容易丢失它。 当然,如果你是在摇滚下编程,你可以做任何你喜欢的事情,但更大的C#社区将感谢你遵循以下标准,特别是在你的代码中使用一致性。