加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何为布尔条件取消合并?

发布时间:2020-12-15 18:12:43 所属栏目:百科 来源:网络整理
导读:我正在尝试安全地检查是否有IList不是空的. var Foo = Bar.GimmeIListT(); // Returns an IListSomeObjectif (Foo?.Any()) // Do cool stuff with items in Foo 但是条件有错误: Cannot implicitly convert ‘bool?’ to ‘bool’. An explicit conversion
我正在尝试安全地检查是否有IList<>不是空的.
var Foo = Bar.GimmeIListT(); // Returns an IList<SomeObject>
if (Foo?.Any())
    // Do cool stuff with items in Foo

但是条件有错误:

Cannot implicitly convert ‘bool?’ to ‘bool’. An explicit conversion exists (are you missing a cast?)

因此,似乎条件评估为可空的布尔,所以我尝试

if (Foo?.Any().Value())

但这也不好:

‘bool’ does not contain a definition for ‘Value’ and no extension …. blah blah blah

因此,在第一种情况下,它抱怨它是一个可以为空的布尔,但在第二种情况下,它抱怨它不是.

作为另一种途径,我尝试:

if (Foo?.Any() == true)

这有效 – 但它不应该因为这使用了第一条消息说它不想要的隐式转换!

到底是怎么回事?这样做的正确方法是什么?

解决方法

你可以比较布尔?如果你使用==,那确实是最好/最简单的方法:
if (Foo?.Any() == true) ...

至于为什么它不允许在if = =,Jon Skeet can explain它更好:

There’s no implicit conversion from Nullable to bool. There is
an implicit conversion from bool to Nullable and that’s what
happens (in language terms) to each of the bool constants in the first
version. The bool operator==(Nullable,Nullable operator
is then applied. (This isn’t quite the same as other lifted operators
– the result is just bool,not Nullable.)

In other words,the expression ‘fred == false’ is of type bool,
whereas the expression ‘fred’ is of type Nullable hence you
can’t use it as the “if” expression.

那么if只允许bool但是你有一个bool?但是==运算符将bool转换为bool?你可以比较两个bool?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读