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?