为什么 "is"-operator 在 if 的范围比 if 更长?

Why is the "is"-operator in an if a longer scope then the if?

所以我的问题是:

为什么(以及如何避免)C# 中的 Is 运算符的生命周期比 if 中使用的更长?

示例:

Animal a = new Cat();
if (a is Cat c)
{
    Console.WriteLine(c); // Works
}

Console.WriteLine(c); // Works too

// Leads to an error because c is allready declared
if (a is Cat c)
{
    ....
}

我期望的是,因为我在 if 条件中声明了变量 c,所以它的范围将限定为该 if 条件,但事实并非如此。

编辑: 我理解括号参数(范围以括号开始并以它结束)。 但是

为什么 for 循环那么不同?

for (int i = 0; i<3; i++)
{
....
}

Console.WriteLine(i) // error

您的期望可能并不总是符合语言规范。我想您可能已经知道 name 但您使用的是 Pattern Matching。 以下是从 MSDN 中获取的 Pattern Matching 范围的规则(我正在复制粘贴相关部分:

public static double ComputeAreaModernIs(object shape)
{
   if (shape is Square s)
       return s.Side * s.Side;
   else if (shape is Circle c)
       return c.Radius * c.Radius * Math.PI;
   else if (shape is Rectangle r)
       return r.Height * r.Length;
    // elided
    throw new ArgumentException(
        message: "shape is not a recognized shape",
        paramName: nameof(shape));
}

The variable c is in scope only in the else branch of the first if statement. The variable s is in scope in the method ComputeAreaModernIs. That's because each branch of an if statement establishes a separate scope for variables. However, the if statement itself doesn't. That means variables declared in the if statement are in the same scope as the if statement (the method in this case.) This behavior isn't specific to pattern matching, but is the defined behavior for variable scopes and if and else statements.

简单地说,您的范围将以 { 开始并以 }

结束