为什么“if”语句中的类型测试会泄漏范围,而“switch”语句中的类型测试却不会?

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

在以下示例方法中,使用

object o
语句和
switch
语句对
if
进行类型测试。这些方法在功能上是相同的。然而,
if
语句不允许在转换
x
时重复使用相同的变量名
object o

为什么

switch
语句允许这样做,而
if
语句不允许?

public sealed class Test
{
    public long GetLengthA(object o)
    {
        switch (o)
        {
            case Stream x:
                {
                    return x.Length;
                }
            case Array x: // <-- this is allowed
                {
                    return x.Length;
                }
        }
        return 0;
    }
    public long GetLengthB(object o)
    {
        if (o is Stream x)
        {
            return x.Length;
        }
        else if (o is Array x) // <-- this is NOT allowed
        {
            return x.Length;
        }
        return 0;
    }
}

错误CS0136:无法在此声明名为“x”的本地或参数 范围,因为该名称在封闭的本地范围中使用来定义 本地或参数

c# if-statement types casting switch-statement
1个回答
0
投票

基本上在 switch-case 中,每个 case 都被视为它自己的作用域,因此您可以重用变量名称,但使用 if-else 梯形图时,整个函数都是作用域,因此您无法真正重用该名称。尝试将第二个变量 x 更改为 y。

看这里, https://dotnetfiddle.net/LFyxXS

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