英文:
Is this a C# switch expression exhaustiveness check bug?
问题
public enum Test { Yes, No }
我有这两个 `switch` 表达式。下面的这个会出现 CS8509 警告:
```cs
Test? test = null;
var result = test switch
{
null => "Null",
Test.Yes => "Yes",
Test.No => "No",
};
但是将 null
情况移动到最后就可以解决。有人知道为什么会这样吗?这一定是一个 bug,对吗?
Test? test = null;
var result = test switch
{
Test.Yes => "Yes",
Test.No => "No",
null => "Null",
};
项目设置:
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>10.0</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoWarn>8524</NoWarn>
</PropertyGroup>
英文:
public enum Test { Yes, No }
I have these two switch
expressions. The one below gives a CS8509 warning:
Test? test = null;
var result = test switch
{
null => "Null",
Test.Yes => "Yes",
Test.No => "No",
};
But moving the null
case to the end resolves it. Does anybody know why this happens? This has to be a bug, correct?
Test? test = null;
var result = test switch
{
Test.Yes => "Yes",
Test.No => "No",
null => "Null",
};
Project settings:
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>10.0</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoWarn>8524</NoWarn>
</PropertyGroup>
答案1
得分: 4
我找到了一个在GitHub上的问题,与您的问题非常相似。解决方案如下:
经过与团队成员的讨论,这是设计意图。编译器的承诺是提供诊断信息,但确切的诊断信息是一个保留的问题,我们对此保持灵活性。
您已经禁用了至少两个可能的警告之一,因此导致了这种不一致的行为。同样的情况也可以反过来复现:
#pragma warning disable CS8509
// 无警告
static void F(Test? test) {
var result = test switch
{
null => "Null",
Test.Yes => "Yes",
Test.No => "No",
};
}
// 警告
static void F(Test? test) {
var result = test switch
{
Test.Yes => "Yes",
Test.No => "No",
null => "Null",
};
}
演示 @sharplab
英文:
Found this issue at the github with very similar problem. The resolution is:
> From discussion with team members, this is by design. The compiler's commitment is to provide a diagnostic, but exactly which diagnostic is a question that's reserved and we keep flexibility on that.
You have disabled one of the (at least) two warnings possible here, so you get this inconsistent behaviour. The same can be reproduced the other way around:
#pragma warning disable CS8509
// no warning
static void F(Test? test) {
var result = test switch
{
null => "Null",
Test.Yes => "Yes",
Test.No => "No",
};
}
// warning
static void F(Test? test) {
var result = test switch
{
Test.Yes => "Yes",
Test.No => "No",
null => "Null",
};
}
Demo @sharplab
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论