空条件运算符和if语句

Cen*_*tro 5 c# c#-6.0 null-conditional-operator

该代码为何起作用:

if (list?.Any() == true)
Run Code Online (Sandbox Code Playgroud)

但是这段代码没有:

if (list?.Any())
Run Code Online (Sandbox Code Playgroud)

错误CS0266无法隐式转换类型“布尔”?“布尔”

那么,为什么不是语言功能在if语句中进行这种隐式转换呢?

Der*_*ler 6

一个if语句将评估Boolean表达。

bool someBoolean = true;

if (someBoolean)
{
    // Do stuff.
}
Run Code Online (Sandbox Code Playgroud)

因为if语句对Boolean表达式求值,所以您尝试做的是从Nullable<bool>. bool

bool someBoolean;
IEnumerable<int> someList = null;

// Cannot implicity convert type 'bool?' to 'bool'.
someBoolean = someList?.Any();
Run Code Online (Sandbox Code Playgroud)

Nullable<T>确实提供了GetValueOrDefault一种可用于避免真假比较的方法。但我认为你的原始代码更清晰。

if ((list?.Any()).GetValueOrDefault())
Run Code Online (Sandbox Code Playgroud)

一个可能吸引您的替代方法是创建您自己的扩展方法。

public static bool AnyOrDefault<T>(this IEnumerable<T> source, bool defaultValue)
{
    if (source == null)
        return defaultValue;

    return source.Any();
}
Run Code Online (Sandbox Code Playgroud)

用法

if (list.AnyOrDefault(false))
Run Code Online (Sandbox Code Playgroud)

  • 我将这个问题解释为“为什么`if`不接受`bool?`条件?” (2认同)