c# 8 switch 表达式不“智能";足够的 [英] c# 8 switch expression not "smart" enough
问题描述
这段代码很简单,只是一个普通的开关:
This code is simple, just a normal switch:
bool? isSomething = strSomething switch
{
"I" => true,
"D" => false,
_ => null,
};
但是,编译器给了我以下错误:
However, the compiler gives me the following error:
CS0037 无法将 null 转换为 'bool',因为它是不可为 null 的值类型
CS0037 Cannot convert null to 'bool' because it is a non-nullable value type
这个变量显然是一个可以为 null 的 bool bool?
,为什么 c# 编译器不能在没有我必须强制转换 null 才能让它工作的情况下弄清楚这一点:
The variable is clearly a nullable bool bool?
, why can't c# compiler figure this out without me having to cast the null to get it to work:
_ => (bool?)null,
我是不是没听明白?演员不是不必要的吗?
Am I not getting this right? isn't the cast unnecessary?
推荐答案
有一个打开的 issue#2387 在 c# 语言中.这可以在 thisCandidate 中针对 c# 9 修复.
There is an opened issue #2387 for this in c# lang. Which could be fixed in this candidate for c# 9.
这篇关于c# 8 switch 表达式不“智能";足够的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!