为什么这段代码有效:
if (list?.Any() == true)
但是这段代码没有:
if (list?.Any())
说错误CS0266无法隐式转换类型“bool?”为“ bool ”
那么,为什么语言功能没有在 if 语句中进行这样的隐式转换呢?
最佳答案
bool someBoolean = true;
if (someBoolean)
{
// Do stuff.
}
因为if
语句评估 Boolean
表达式,您尝试做的是从 Nullable<bool>
. 进行隐式转换至bool
.
bool someBoolean;
IEnumerable<int> someList = null;
// Cannot implicity convert type 'bool?' to 'bool'.
someBoolean = someList?.Any();
Nullable<T>
确实提供了 GetValueOrDefault
可以用来避免真假比较的方法。但我认为你的原始代码更干净。
if ((list?.Any()).GetValueOrDefault())
可能对您有吸引力的另一种选择是创建您自己的扩展方法。
public static bool AnyOrDefault<T>(this IEnumerable<T> source, bool defaultValue)
{
if (source == null)
return defaultValue;
return source.Any();
}
使用
if (list.AnyOrDefault(false))
关于c# - 使用空条件 bool ?在 if 语句中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45596941/