所以我的问题是:
为什么(以及如何避免这种情况)C#中的Is-operator的寿命比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-condition中声明了变量c,所以它将范围限定于if-condition,这是不正确的。
编辑:我理解方括号参数(范围以括号开头,以其结尾)。但
为什么for循环那么不同呢?
for (int i = 0; i<3; i++)
{
....
}
Console.WriteLine(i) // error
您所期望的可能并不总是始终符合语言规范。我认为您可能已经知道了名称,但是您正在使用的名称称为Pattern Matching
。这是从MSDN提取的模式匹配范围的规则(我正在复制粘贴相关部分:
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));
}
变量c仅在第一个if语句的else分支中起作用。变量s在ComputeAreaModernIs方法的范围内。这是因为if语句的每个分支为变量建立了单独的作用域。但是,if语句本身没有。这意味着在if语句中声明的变量与if语句(在这种情况下为方法)在同一范围内。此行为不是特定于模式匹配的,而是变量范围以及if和else语句的已定义行为。
简单地说你的范围将开始{
和结束与}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句