c# – 正确使用EventArgs

我有一个非常基本的事件:

public event EventHandler OnAborted;

我需要做的就是调用这个事件,我甚至不需要提供任何参数,所以它没什么特别的.我对EventArgs参数的正确用法感到困惑.

我可以用:

if (OnAborted != null)
   OnAborted(this, EventArgs.Empty);

或者我甚至可以使用:

if (OnAborted != null)
   OnAborted(this, new EventArgs());

在这两种情况下,EventArgs似乎都没用,我甚至无法提供任何参数(不是我需要的,但这不是重点).

EventArgs的正确用法是什么?我应该创建一个继承EventArgs的自定义类吗?

最佳答案 使用EventArgs.Empty不会创建新对象并在堆上分配它.更重要的是,EventArgs.Empty是
Null Object Pattern的一个实例.拥有一个表示“无值”的对象,以避免在使用它时检查null.

要在您应该使用EventArgs或正确的类时添加更多内容,这里有一些关于事件设计的MSDN指南:

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

If you define an event that takes an EventArgs instance instead of a derived class that you define, you cannot add data to the event in later versions. For that reason, it is preferable to create an empty derived class of EventArgs. This allows you add data to the event in later versions without introducing breaking changes.

点赞