IS"的ReferenceEquals(myObject的,空)QUOT; myObject的== NULL"?;比&QUOT更好的做法

编程入门 行业动态 更新时间:2024-10-28 08:25:45
本文介绍了IS"的ReferenceEquals(myObject的,空)QUOT; myObject的== NULL"?;比&QUOT更好的做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

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

如果(myObject的!= NULL)

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

解决方案   

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

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

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

本文发布于:2023-06-06 06:21:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/538991.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:做法   ReferenceEquals   QUOT   NULL   myObject

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!