gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:47:07 24 4
gpt4 key购买 nike

为什么这段代码有效:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com