gpt4 book ai didi

c# - 没有参数的 Event 应该定义自己的自定义 EventArgs 还是简单地使用 System.EventArgs?

转载 作者:可可西里 更新时间:2023-11-01 08:18:59 29 4
gpt4 key购买 nike

我有一个当前定义的没有事件参数的事件。即它发送的EventArgs是EventArgs.Empty。

在这种情况下,最简单的方法是将我的事件处理程序声明为:

EventHandler<System.EventArgs> MyCustomEvent;

我不打算向该事件添加任何事件参数,但将来可能需要更改任何代码。

因此,我倾向于让我的所有事件始终创建一个从 System.EventArgs 继承的空事件参数类型,即使当前不需要事件参数。像这样:

public class MyCustomEventArgs : EventArgs
{
}

然后我的事件定义变成如下:

EventHandler<MyCustomEventArgs> MyCustomEvent;

所以我的问题是:定义我自己的 MyCustomEventArgs 是否更好,即使它除了从 System.EventArgs 继承之外没有添加任何东西,所以事件参数将来可以更容易地添加吗?还是将我的事件显式定义为返回 System.EventArgs 更好,这样用户就更清楚没有额外的事件参数?

我倾向于为所有事件创建自定义事件参数,即使事件参数为空。但我想知道其他人是否认为让用户更清楚地知道事件参数为空会更好?

非常感谢,

迈克

最佳答案

来自 Brad Abrams 和 Krzysztof Cwalina 的 Framework Design Guidelines:

Consider using a subclass of EventArgs as the event argument, unless you are absolutely sure the event will never need to carry any data to then event handling method, in which case you can use the EventArgs type directly.

If you ship an API using EventArgs directly, you will never be able to add any data to be carried with the event without breaking compatibility. If you use a subclass, even if initially completely empty, you will be able to add properties to the subclass when needed.

我个人认为这归结为兼容性问题。如果你正在制作一个供其他人使用的类库,那么我会使用一个子类。如果您仅在自己的代码中使用事件,那么(正如 Alfred 所说),YAGNI 适用。当您从 EventArgs 更改为您自己的派生类时,这将是一个重大更改,但由于它只会破坏您自己的代码,因此问题不大。

关于c# - 没有参数的 Event 应该定义自己的自定义 EventArgs 还是简单地使用 System.EventArgs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1318543/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com