c# - 使用空条件 bool ?在 if 语句中

标签 c# c#-6.0 null-conditional-operator

为什么这段代码有效:

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

但是这段代码没有:

if (list?.Any())

错误CS0266无法隐式转换类型“bool?”为“ bool ”

那么,为什么语言功能没有在 if 语句中进行这样的隐式转换呢?

最佳答案

if 语句将评估 Boolean 表达。

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/

相关文章:

c# - 为什么在不使用可为空的 bool 的情况下设置 bool 的值时可以使用 null 条件运算符?

vb.net - 否定 null 条件运算符会毫无结果地返回意外结果

c# - 在 Stream 中找到给定字节序列开始位置的最佳方法

c# - 鼠标滚轮滚动工具条菜单项

linq - EF core 2第一次查询慢

c# - C# 6.0 的字符串插值是否依赖于反射?

c# - 如何将 Nullable 运算符与 Null 条件运算符一起使用?

c# - 捕捉到网格鼠标锁定

c# - Windows Phone PhoneGap 应用后退按钮问题

c# - 自动属性初始化器单例实现