开关类型模式使用的奇怪编译器行为

问题描述 投票:0回答:1

在下面的代码中,无论我尝试访问

s
还是
o
都没有关系,在这两种情况下,编译器都会抱怨变量未初始化。我希望至少
o
始终被初始化,因为它是最不具体的类型。那么为什么编译器甚至允许我在这种情况下指定变量呢?

void Foo(object obj)
{       
        switch (obj)
        {
            case string s:
            case object o:
                Console.WriteLine(s);
                break;
        }      
}
        

我正在使用.NET 7。

c# .net compiler-errors pattern-matching c#-7.0
1个回答
0
投票

来自文档

switch 语句执行 first switch 部分中的语句列表,其 case 模式与匹配表达式匹配,并且其 case 保护(如果存在)计算结果为 true

所以我认为这实际上是预料之中的。你有两条路通向

Console.WriteLine
。在伪代码中,它看起来像这样:

string s;
object o;

if(obj is string)
{
   s = (string) obj;
   goto doSomething;
}


if(obj is object)
{
   o = (object) obj;
   goto doSomething;
}

doSomething:
// your Console.WriteLine here
// Console.WriteLine(s); Local variable 's' might not be initialized before accessing
// Console.WriteLine(o); Local variable 'o' might not be initialized before accessing

因此,如果一个匹配,另一个将不会被处理(因为没有理由)导致其中一个变量未被初始化。

© www.soinside.com 2019 - 2024. All rights reserved.