IS"的ReferenceEquals(myObject的,空)QUOT; myObject的== NULL"?;比&QUOT更好的做法 [英] Is "ReferenceEquals(myObject, null)" better practice than "myObject == null"?

查看:125
本文介绍了IS"的ReferenceEquals(myObject的,空)QUOT; myObject的== NULL"?;比&QUOT更好的做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个同事谁是写他的null检查如下的粉丝:

 如果(!的ReferenceEquals(myObject的,空))
 

我,在另一方面,发现这繁琐的语法阅读和preFER:

 如果(myObject的!= NULL)
 

我已经找到了一些文章和堆栈溢出问题讨论的ReferenceEquals的优点相对于操作符重载,但操作符重载的情况外,没有任何好处的ReferenceEquals VS ==?

解决方案
  

但操作符重载的情况外,没有任何好处的ReferenceEquals VS ==?

没有 - 唯一的好处(我要说这不是多大的优势)显式地使用 Object.ReferenceEquals 将它永远不会使用重载运算符平等的。在非超载的情况下, ==操作符被定义为返回true,如果它的两个操作数指的是同一个对象的所有字符串以外的引用类型。因此,它的等效(只要它不超载)。

我个人也倾向于使用第二个语法,并发现它更易于维护的空检查。我还认为,任何重载 ==操作符还应提供对<​​code>空适当的检查,并在情况下,它并没有因为某些原因(这将是奇怪的),有可能会是,决定背后特定的理由这将导致您要使用的过载,而不是的ReferenceEquals

I have a co-worker who's a fan of writing his null checks as follows:

if (!ReferenceEquals(myObject, null))

I, on the other hand, find this syntax cumbersome to read and prefer:

if (myObject != null)

I've found some articles and stack overflow questions discussing the merits of ReferenceEquals with respect to operator overloading, but outside of the operator overloading scenario, is there any benefit to ReferenceEquals vs == ?

解决方案

but outside of the operator overloading scenario, is there any benefit to ReferenceEquals vs == ?

No - the only advantage (and I'd argue it's not much of an advantage) to explicitly using Object.ReferenceEquals would be that it will never use the overloaded operator equals. In the non-overloaded case, the == Operator is defined to "returns true if its two operands refer to the same object" for all "reference types other than string". As such, its equivalent (provided its not overloaded).

I, personally, also favor using the second syntax, and find it more maintainable for null checking. I'd also argue that any overloaded operator== should also provide proper checking against null, and in the case where it did not for some reason (which would be odd), there'd likely be a specific rationale behind that decision which would cause you to want to use the overload, not ReferenceEquals.

这篇关于IS&QUOT;的ReferenceEquals(myObject的,空)QUOT; myObject的== NULL&QUOT;?;比&QUOT更好的做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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