C#:与 null 比较
它们是否等价:
if (null==myobject)
{
//do something
}
或者
if (myobject==null)
{
//do something
}
它们会产生不同的代码吗?
Are these equivalent:
if (null==myobject)
{
//do something
}
and
if (myobject==null)
{
//do something
}
or will they produce different code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在 99% 的情况下,这段代码是等效的。
一个例外是当相关对象的类型覆盖 == 运算符时。 == 中可能会引入一个错误,当一个参数为空时,该错误会导致出现问题。
我之前见过的一个特定示例如下:
当 null 位于左侧时,这将失败,但当 null 位于右侧时,这可能不会失败。
但这是一个相当遥远的极端情况。
In the 99% case this code is equivalent.
The one exception is when the type of the object in question overrides the == operator. It's possible for a bug to be introduced in == which causes problems when one parameter is null.
A particular example I've seen before is the following
This will fail when null is on the left, but likely not when null in on the right.
This is a pretty far out corner case though.
将常量放在左侧的“
if
”语句的形式是 C/C++ 的保留,在 C/C++ 中,您可以在 if 语句中使用任意表达式。C# 的 if 语句语法要求表达式计算结果为 bool,这意味着
if (foo = 0)
将无法编译。The form of "
if
" statement that puts the constant at the left is a holdover from C/C++ where you could have an arbitrary expression in an if statement.C#'s syntax for if statements requires that the expression evaluate to a bool which means that
if (foo = 0)
won't compile.这
是编写 if 语句的安全方法。 它来自 C/C++,其中条件是计算结果为
int
的表达式。 如果结果为零,则表示false
,其他均为true
。 你可以这样写,但如果你不小心,你也可以这样写,
在这种情况下,你的赋值总是为 1,因此总是 true。
您可以编译并运行它,没有任何问题,但结果不会是您所期望的。 所以 C/C++ 程序员开始写这样的东西:
如果你拼错了,这将无法编译,所以你总是必须按照你想要写的方式来写。 这后来成为一种(好)习惯,并且您可以在所有编程语言中使用它,例如 C#。
The
is a safe way of writing an if statement. It comes from C/C++ where the condition is an expression evaluated to an
int
. If the result is zero that meansfalse
, anything else istrue
. You could write something likebut if you weren’t careful you could also write
in which case you have an assignment that always evaluates to 1 and thus is always true.
You could compile this and run it with no problems, but the result wouldn’t be what you expected. So C/C++ programmers started to write things like
This won’t compile if you misspell it, so you always had to write it as you meant to write it. This later becomes a (good) habit and you use it in all the languages you program with, C# for example.
对于那些错过它的人,如果您希望减少混乱,也可以为您的
C#
类启用C 语言
样式的空检查:For those who miss it, of if you're looking to reduce clutter, it's also possible to enable
C-language
-style null-checking for yourC#
classes:正如其他人指出的那样,它们大多是等效的。
您还应该看看:
http://en.wikipedia.org/wiki/Null_Object_pattern
这是一个非常有用的替代方案只需检查空引用即可。
As pointed out by others they are mostly equivalent.
You should also take a look at:
http://en.wikipedia.org/wiki/Null_Object_pattern
It is a very useful alternative to simply checking for a null reference.
除非您重载 ==,否则两种情况都会产生相同的结果。
Unless you overload ==, both cases produce the same results.