考虑以下示例:
public static double ComputeArea_Version3(object shape)
{
switch (shape)
{
case Square s when s.Side == 0:
case Circle c when c.Radius == 0:
return 0;
case Square s:
return s.Side * s.Side;
case Circle c:
return c.Radius * c.Radius * Math.PI;
default:
throw new ArgumentException(
message: "shape is not a recognized shape",
paramName: nameof(shape));
}
}
when
子句case Square s when s.Side == 0:
是否保证在更通用的case Square s:
之前执行? 是什么决定了这个顺序,是在switch
中的位置吗? 如果我改为以下方式是否正确:
public static double ComputeArea_Version3(object shape)
{
switch (shape)
{
case Square s:
return s.Side * s.Side;
case Circle c:
return c.Radius * c.Radius * Math.PI;
case Square s when s.Side == 0:
case Circle c when c.Radius == 0:
return 0;
default:
throw new ArgumentException(
message: "shape is not a recognized shape",
paramName: nameof(shape));
}
}
< p >这些< code >when条件从未被评估吗?< /p >
return
行,因此它不会到达后续的 case 语句。 - Kristianne Nerona