【发布时间】:2018-04-03 07:04:36
【问题描述】:
怎么可能跟随?
switch (param.ParameterType)
{
case Type x when x == typeof(byte):
int invalid;
break;
case Type x when x == typeof(short):
int invalid;
break;
case Type x when x == typeof(int):
break;
case Type x when x == typeof(long):
break;
}
问题是,x 如何在每个案例中限定范围而没有任何可见块。同时,变量invalid不能在不同的switch case中声明。它必须在一个块内。
如果没有块,那么跟踪变量的范围是不可能的。
{
// case byte:
Type x;
int invalid;
// break;
// case short:
Type x; // x can not be declared twice.
int invalid;
}
如果每个案例都有不可见的块,那么跟随必须是可能的(但不是)。
{
{ // block for each case.
// case byte:
Type x;
int invalid;
// break;
}
{
// case short:
Type x;
int invalid; // but this throws compile time error.
}
}
似乎编译器在这里做了一些魔术,显然x 的作用域不同于invalid 变量。这是编译器语义分析阶段的错误吗?
【问题讨论】:
标签: c# scope switch-statement variable-declaration c#-7.0