为什么使用EventArgs.Empty而不是null?[英] Why use EventArgs.Empty instead of null?

本文是小编为大家收集整理的关于为什么使用EventArgs.Empty而不是null?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我回想起在发射典型事件时多次和多个位置阅读:

protected virtual OnSomethingHappened()
{
    this.SomethingHappened(this, EventArgs.Empty);
}

e应该是eventargs.

我已经按照我的代码遵循了指导,但是我意识到我尚不清楚为什么这是首选技术.为什么规定的合同更喜欢EventArgs.empty而不是null?

推荐答案

我相信不是零零背后的原因是,当作为参数传递时,该方法不希望能够潜在地处理零参考异常.

.

如果您通过null,并且该方法试图使用E进行null引用异常,则使用EventArgss.Empty不会.

其他推荐答案

EventArgs.Empty是 null object quote .

基本上,拥有一个代表"无值"的对象以避免使用null时检查null.

其他推荐答案

我相信EventArgs.Empty即使不需要,EventArgs.Empty也用于维持与事件传递论证的约定.

米切尔卖家在我的帖子中间发布了我的另一半,我的帖子中的另一半是:它可以防止使用方法并使用该参数做点事(除了检查是否为null).

.

EventArgs.Empty基本上是在没有其他信息的情况下进行全球定义的事件参数的工作.

给出了维护约定的类似示例,我们的团队使用string.Empty来初始化字符串,因为否则不同的编码器可能会使用newString = ""; or newString = " "; or newString = null;,所有这些都可能在不同的检查条件下产生不同的结果.

a(稍微ped)使用EventArgs.Empty vs new EventArgs()的原因是前者不初始化新的EventArgs,节省了少量的内存.

本文地址:https://www.itbaoku.cn/post/627414.html

问题描述

I recall reading, on multiple occasions and in multiple locations, that when firing the typical event:

protected virtual OnSomethingHappened()
{
    this.SomethingHappened(this, EventArgs.Empty);
}

e should be EventArgs.Empty if there are no interesting event args, not null.

I've followed the guidance in my code, but I realized that I'm not clear on why that's the preferred technique. Why does the stated contract prefer EventArgs.Empty over null?

推荐答案

I believe the reasoning behind the NOT NULL is that when passed as a parameter, it is not expected for the method to need to potentially handle a null reference exception.

If you pass null, and the method tries to do something with e it will get a null reference exception, with EventArgs.Empty it will not.

其他推荐答案

EventArgs.Empty is an instance of the Null object pattern.

Basically, having an object representing "no value" to avoid checking for null when using it.

其他推荐答案

I believe EventArgs.Empty is used to maintain the convention of passing an argument with an event, even if none are needed.

Mitchel Sellers posted the other half of my reason halfway through my post: it prevents a null reference exception should a method try and do something with that argument (besides check if it is null).

EventArgs.Empty basically does the work of a globally defined Event Argument with no additional information.

To give a similar example of maintaining a convention, our team uses string.Empty to initialize a string because otherwise different coders might use newString = ""; or newString = " "; or newString = null;, all of which may produce different results for different check conditions.

A (slightly pedantic) reason to use EventArgs.Empty vs new EventArgs() is that the former does not initialize a new EventArgs, saving a slight amount of memory.