有很多语法糖与可空< T>
像:
诠释?解析到可空< INT>
诠释? X =空
如果(X!= NULL)//解析为IF(x.HasValue)
X = 56; //解析,以x.Value = 56;
等等。
为什么如果
条件可空不起作用?
如果(X)
{}
它让编者错误说不能转换可空<布尔>
到布尔
为什么它没有被解析到如果(x.HasValue&安培;&安培; x.Value ==真)?
或类似的东西。
这是最明显的用法可空<布尔>
这是最明显的用法可空<布尔>
您显而易见的行为导致许多inobvious行为。
如果
如果(X)
被视为假时,x为空,那么会发生什么,以
如果(!X)
? !X
也为空当x是空的,因此也将被视为假的!它似乎并不奇怪,你不能扭转有条件的行为与反转?
什么
如果(X |!X)
当然,应该永远是正确的,但如果x为null,则整个EX pression是空的,因此假的。
这是更好地通过简单地让他们所有非法避免这些inobvious情况。 C#是一种使用户说他们是什么意思明确的语言。
我相信,VB有你想要的行为。你可能会考虑换用VB,如果这是你喜欢的那类事情。
There is a lot of syntax sugar with Nullable<T>
like those:
int? parsed to Nullable<int>
int? x = null
if (x != null) // Parsed to if (x.HasValue)
x = 56; // Parsed to x.Value = 56;
And more.
Why if
condition with Nullable doesn't work?
if (x)
{}
It gets Complier error saying can't convert Nullable<bool>
to bool
.
Why it's not being parsed to if (x.HasValue && x.Value == true)
or something similar?
It's the most obvious usage for Nullable<bool>
It's the most obvious usage for Nullable<bool>
Your "obvious" behaviour leads to many inobvious behaviours.
If
if(x)
is treated as false when x is null, then what should happen to
if(!x)
? !x
is also null when x is null, and therefore will be treated as false also! Does it not seem strange that you cannot reverse the behaviour of a conditional with an inversion?
What about
if (x | !x)
Surely that should always be true, but if x is null then the whole expression is null, and therefore false.
It is better to avoid these inobvious situations by simply making them all illegal. C# is a "make the user say what they mean unambiguously" language.
I believe that VB has the behaviour you want. You might consider switching to VB if this is the sort of thing you like.