如果条件可以为空

if condition with nullable(如果条件可以为空)

本文介绍了如果条件可以为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Nullable<T> 有很多语法糖,比如:

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;

还有更多.

为什么带有 Nullable 的 if 条件不起作用?

Why if condition with Nullable doesn't work?

if (x)
{} 

编译器错误提示无法将 Nullable<bool> 转换为 bool.
为什么它没有被解析为 if (x.HasValue && x.Value == true) 或类似的东西?

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?

这是 Nullable<bool>

推荐答案

这是 Nullable<bool>

你的明显"行为会导致许多不明显的行为.

Your "obvious" behaviour leads to many inobvious behaviours.

如果

if(x)

当x为null时被视为假,那么应该发生什么

is treated as false when x is null, then what should happen to

if(!x)

?当 x 为 null 时 !x 也为 null,因此也将被视为 false!不能用倒置来反转条件的行为似乎并不奇怪?

? !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?

怎么样

if (x | !x)

当然,这应该始终为真,但如果 x 为空,则整个表达式为空,因此为假.

Surely that should always be true, but if x is null then the whole expression is null, and therefore false.

最好通过简单地将它们全部设为非法来避免这些不明显的情况.C# 是一种让用户明确说出他们的意思"的语言.

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.

我相信 VB 有你想要的行为.如果您喜欢这种方式,您可以考虑切换到 VB.

I believe that VB has the behaviour you want. You might consider switching to VB if this is the sort of thing you like.

这篇关于如果条件可以为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如果条件可以为空

基础教程推荐