(0 ==变量)或(空== OBJ):一个过时的做法在C#中? [英] (0 == variable) or (null == obj): An outdated practice in C#?

查看:198
本文介绍了(0 ==变量)或(空== OBJ):一个过时的做法在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<一个href="http://stackoverflow.com/questions/271561/why-does-one-often-see-null-variable-instead-of-variable-null-in-c">Why做一件经常看到空!=变量,而不是变!= NULL在C#?

我见过用在标题中提到的语法高级开发人员。

是否需要指定一个恒定的第一.NET? (如C / C ++的世界反对)

I have seen senior developers using syntaxes mentioned in the title.

Is there a need for specifying a constant first in .NET? (as opposed to in C/C++ world)

推荐答案

没有,没有必要为这个,因为这个问题是试图避免 - 即错字:

No, there's no need for this, because the problem it tries to avoid - namely the typo of:

if (variable = 0)

不会在C#编译反正。在的条件,如果语句必须是布尔值。目前仍然使得这些错误之一的风险:

wouldn't compile in C# anyway. The conditions in if statements have to be Boolean. There's still a risk of making one of these mistakes:

if (something = true)
if (something = false)

如果的东西是一个布尔变量,但更好的办法来解决,这是为了避免恒:

if something is a Boolean variable, but the better way to fix this is to avoid the constant:

if (something)
if (!something)

如果您有开发人员带来了成语像这样从其他语言,而不考虑它们是否适合在C#中,你应该关注他们做更多的相同。如果您尝试写C#,如果是C ++(或任何其他语言,pretty的多 - 用VB.NET可能是个例外)。你最终会写入不地道的C#code

If you have developers bringing over idioms like this from other languages without thinking about whether they're appropriate in C#, you should keep an eye for them doing more of the same. If you try to write C# as if it's C++ (or any other language, pretty much - with the possible exception of VB.NET) you'll end up writing non-idiomatic C# code.

编辑:克莱图斯指出,还有的的关注另一个潜在领域:

As cletus noted, there is another potential area for concern:

bool a = false, b = true; 
if (a = b) { } // No warnings

因此​​,错误仍然可能发生 - 但我们无论如何以恒定比较领域之外:)我会说这庄稼了令人难以置信的很少,而且不值得太多的时间花在担心它

So the error can still occur - but then we're outside the realm of comparing with a constant anyway :) I'd say this crops up incredibly rarely, and isn't worth too much time spent worrying about it.

这篇关于(0 ==变量)或(空== OBJ):一个过时的做法在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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