为什么在 C# 中经常看到“null != variable”而不是“variable != null”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/271561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does one often see "null != variable" instead of "variable != null" in C#?
提问by mr_georg
In c#, is there any difference in the excecution speed for the order in which you state the condition?
在 c# 中,您陈述条件的顺序在执行速度上有什么不同吗?
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?
如果没有区别,第一个的优势是什么?
采纳答案by Jon Skeet
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):
这是 C 的保留。在 C 中,如果您使用错误的编译器或没有足够高的警告,则编译时不会发出任何警告(并且确实是合法代码):
// Probably wrong
if (x = 5)
when you actually probably meant
当你实际上可能的意思是
if (x == 5)
You can work around this in C by doing:
您可以通过执行以下操作在 C 中解决此问题:
if (5 == x)
A typo here will result in invalid code.
这里的拼写错误会导致代码无效。
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
.
现在,在 C# 中,这一切都是小菜一碟。除非您比较两个布尔值(这种情况很少见,IME),否则您可以编写更具可读性的代码,因为“if”语句需要以布尔表达式开头,而“ x=5
”的类型是Int32
,不是Boolean
。
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.
我建议,如果您在同事的代码中看到这一点,请以现代语言的方式教育他们,并建议他们将来编写更自然的形式。
回答by Lasse V. Karlsen
I guess this is a C programmer that has switched languages.
我猜这是一个切换语言的 C 程序员。
In C, you can write the following:
在 C 中,您可以编写以下内容:
int i = 0;
if (i = 1)
{
...
}
Notice the use of a single equal sign there, which means the code will assign 1 to the variable i, then return 1 (an assignment is an expression), and use 1 in the if-statement, which will be handled as true. In other words, the above is a bug.
注意这里使用了一个等号,这意味着代码将给变量 i 赋值 1,然后返回 1(赋值是一个表达式),并在 if 语句中使用 1,这将被处理为 true。换句话说,上面是一个错误。
In C# however, this is not possible. There is indeed no difference between the two.
然而,在 C# 中,这是不可能的。两者之间确实没有区别。
回答by Rik
In earlier times, people would forget the '!' (or the extra '=' for equality, which is more difficult to spot) and do an assignment instead of a comparison. putting the null in front eliminates the possibility for the bug, since null is not an l-value (I.E. it can't be assigned to).
在更早的时候,人们会忘记“!” (或额外的 '=' 表示相等,这更难发现)并进行赋值而不是比较。将空值放在前面可以消除错误的可能性,因为空值不是左值(即不能分配给它)。
Most modern compilers give a warning when you do an assignment in a conditional nowadays, and C# actually gives an error. Most people just stick with the var == null scheme since it's easier to read for some people.
现在大多数现代编译器在您在条件中进行赋值时都会发出警告,而 C# 实际上会给出错误。大多数人只是坚持使用 var == null 方案,因为它对某些人来说更容易阅读。
回答by TheCodeJunkie
To me it's always been which style you prefer
对我来说一直是你喜欢哪种风格
@Shy - Then again if you confuse the operators then you should want to get a compilation error or you will be running code with a bug - a bug that come back and bite you later down the road since it produced unexpected behaviour
@Shy - 再说一次,如果你混淆了操作符,那么你应该想要得到一个编译错误,否则你将运行带有错误的代码 - 这个错误会在以后回来并咬你,因为它产生了意外的行为
回答by karlipoppins
One more thing... If you are comparing a variable to a constant (integer or string for ex.), putting the constant on the left is good practice because you'll never run into NullPointerExceptions :
还有一件事......如果您将变量与常量(例如整数或字符串)进行比较,将常量放在左侧是一种很好的做法,因为您永远不会遇到 NullPointerExceptions :
int i;
if(i==1){ // Exception raised: i is not initialized. (C/C++)
doThis();
}
whereas
然而
int i;
if(1==i){ // OK, but the condition is not met.
doThis();
}
Now, since by default C# instanciates all variables, you shouldn't have that problem in that language.
现在,由于默认情况下 C# 实例化所有变量,您在该语言中不应该有这个问题。
回答by DanW
There is a good reason to use null first: if(null == myDuck)
首先使用 null 是有充分理由的: if(null == myDuck)
If your class Duck
overrides the ==
operator, then if(myDuck == null)
can go into an infinite loop.
如果您class Duck
覆盖了==
运算符,则if(myDuck == null)
可以进入无限循环。
Using null
first uses a default equality comparator and actually does what you were intending.
Using null
first 使用默认的相等比较器并实际执行您的意图。
(I hear you get used to reading code written that way eventually - I just haven't experienced that transformation yet).
(我听说您最终习惯了阅读以这种方式编写的代码 - 我只是还没有经历过这种转变)。
Here is an example:
下面是一个例子:
public class myDuck
{
public int quacks;
static override bool operator ==(myDuck a, myDuck b)
{
// these will overflow the stack - because the a==null reenters this function from the top again
if (a == null && b == null)
return true;
if (a == null || b == null)
return false;
// these wont loop
if (null == a && null == b)
return true;
if (null == a || null == b)
return false;
return a.quacks == b.quacks; // this goes to the integer comparison
}
}
回答by Oliver
Like everybody already noted it comes more or less from the C language where you could get false code if you accidentally forget the second equals sign. But there is another reason that also matches C#: Readability.
就像每个人已经注意到的那样,它或多或少来自 C 语言,如果您不小心忘记了第二个等号,您可能会得到错误代码。但是还有另一个与 C# 匹配的原因:可读性。
Just take this simple example:
就拿这个简单的例子来说:
if(someVariableThatShouldBeChecked != null
&& anotherOne != null
&& justAnotherCheckThatIsNeededForTestingNullity != null
&& allTheseChecksAreReallyBoring != null
&& thereSeemsToBeADesignFlawIfSoManyChecksAreNeeded != null)
{
// ToDo: Everything is checked, do something...
}
If you would simply swap all the nullwords to the beginning you can much easier spot all the checks:
如果您简单地将所有空词交换到开头,您可以更容易地发现所有检查:
if(null != someVariableThatShouldBeChecked
&& null != anotherOne
&& null != justAnotherCheckThatIsNeededForTestingNullity
&& null != allTheseChecksAreReallyBoring
&& null != thereSeemsToBeADesignFlawIfSoManyChecksAreNeeded)
{
// ToDo: Everything is checked, do something...
}
So this example is maybe a bad example (refer to coding guidelines) but just think about you quick scroll over a complete code file. By simply seeing the pattern
所以这个例子可能是一个不好的例子(参考编码指南),但想想你快速滚动一个完整的代码文件。通过简单地看到模式
if(null ...
you immediately know what's coming next.
你立即知道接下来会发生什么。
If it would be the other way around, you always have to scanto the end of the line to see the nullity check, just letting you stumble for a second to find out what kind of check is made there. So maybe syntax highlighting may help you, but you are always slower when those keywords are at the end of the line instead of the front.
如果是相反的方式,您总是必须扫描到行尾才能看到无效检查,只是让您绊倒一秒钟以找出那里进行了什么样的检查。所以也许语法高亮可能对你有帮助,但是当这些关键字位于行尾而不是行首时,你总是会变慢。
回答by Gokkula Sudan R
I don't see any advantage in following this convention. In C, where boolean types don't exist, it's useful to write
我认为遵循这个约定没有任何好处。在 C 中,布尔类型不存在,编写
if( 5 == variable)
rather than
而不是
if (variable == 5)
because if you forget one of the eaqual sign, you end up with
因为如果你忘记了一个等号,你最终会得到
if (variable = 5)
which assigns 5 to variable and always evaluate to true. But in Java, a boolean is a boolean. And with !=, there is no reason at all.
它将 5 分配给变量并始终评估为真。但是在 Java 中,布尔值是一个布尔值。而有了 !=,就完全没有理由了。
One good advice, though, is to write
不过,一个好的建议是写
if (CONSTANT.equals(myString))
rather than
而不是
if (myString.equals(CONSTANT))
because it helps avoiding NullPointerExceptions.
因为它有助于避免 NullPointerExceptions。
My advice would be to ask for a justification of the rule. If there's none, why follow it? It doesn't help readability
我的建议是要求对规则进行论证。如果没有,为什么要遵循它?它无助于可读性