为什么人们经常看到"!=空可变的QUOT;代替"!变量=空"在C#中? [英] Why does one often see "null != variable" instead of "variable != null" in C#?
问题描述
在C#中,有没有在你状态的条件才能在excecution速度有什么区别?
In c#, is there any difference in the excecution speed for the order in which you state the condition?
if (null != variable) ...
if (variable != null) ...
最近以来,我看到的第一个经常,这引起了我的注意,因为我是用第二个。
Since recently, I saw the first one quite often, and it caught my attention since I was used to the second one.
如果没有区别,什么是第一位的优势在哪里?
If there is no difference, what is the advantage of the first one?
推荐答案
这是一个滞留在从C.在C语言中,如果你要么使用一个糟糕的编译器或没有警告调到足够高,这将编译没有任何警告(不愧是合法code):
It's a hold-over from C. In C, if you either use a bad compiler or don't have warnings turned up high enough, this will compile with no warning whatsoever (and is indeed legal code):
// Probably wrong
if (x = 5)
当你真正大概意思
when you actually probably meant
if (x == 5)
您可以解决这在C做:
if (5 == x)
这里的一个错字会导致无效code。
A typo here will result in invalid code.
现在,在C#中,这是所有的废话。除非你比较两个布尔值(这是罕见的,IME),您可以编写更加易读code,作为一个如果语句需要布尔前pression入手,和类型 X = 5
是的Int32
,而不是布尔
。
Now, in C# this is all piffle. Unless you're comparing two Boolean values (which is rare, IME) you can write the more readable code, as an "if" statement requires a Boolean expression to start with, and the type of "x=5
" is Int32
, not Boolean
.
我建议,如果你看到你的同事的code,你教育他们在现代语言的方式,并建议他们写在未来的更自然的方式。
I suggest that if you see this in your colleagues' code, you educate them in the ways of modern languages, and suggest they write the more natural form in future.
这篇关于为什么人们经常看到"!=空可变的QUOT;代替"!变量=空"在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!