问题描述
原因是 null
在条件条件下不评估为 false
是什么原因?
What is the reason null
doesn't evaluate to false
in conditionals?
我首先想到了赋值,以避免使用 =
而不是 ==
的错误
I first thought about assignments to avoid the bug of using =
instead of ==
, but this could easily be disallowed by the compiler.
if (someClass = someValue) // cannot convert someClass to bool. Ok, nice
if (someClass) // Cannot convert someClass to bool. Why?
if (someClass != null) // More readable?
我认为假设 null
表示 false
。还有其他语言也使用此语言,因此我没有bug。
I think it's fairly reasonable to assume that null
means false
. There are other languages that use this too, and I've not had a bug because of it.
编辑:当然是指引用类型。
Daniel Earwicker对赋值错误的一个很好的评论...编译时没有警告,因为它的评估结果是 bool
:
A good comment by Daniel Earwicker on the assignment bug... This compiles without a warning because it evaluates to bool
:
bool bool1 = false, bool2 = true;
if (bool1 = bool2)
{
// oops... false == true, and bool1 became true...
}
推荐答案
这是C#语言的特定设计功能:。
It's a specific design feature in the C# language: if
statements accept only a bool
.
IIRC是出于安全考虑:具体来说,这样您的第一个 if(someClass = someValue)
无法编译。
IIRC this is for safety: specifically, so that your first if (someClass = someValue)
fails to compile.
编辑:一个好处是,它使 if(42 = = i)
约定( yoda比较)。
One benefit is that it makes the if (42 == i)
convention ("yoda comparisons") unnecessary.
这篇关于为什么不将null评估为false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!