为什么在C#switch语句中,对于在多种情况下使用的变量,仅在第一种情况下才声明它?例如,以下内容引发错误“此范围中已经定义了一个名为'variable'的局部变量”。switch (Type){ case Type.A: string variable = "x"; break; case Type.B: string variable = "y"; break;}但是,根据逻辑,如果类型为,则不应单击初始声明Type.B。switch语句中的所有变量是否都在单个作用域中,并且是否在处理任何逻辑之前创建/分配了它们?
3 回答
当年话下
TA贡献1890条经验 获得超9个赞
如果您希望变量作用于特定情况,则只需将该情况放在其自己的块中:
switch (Type)
{
case Type.A:
{
string variable = "x";
/* Do other stuff with variable */
}
break;
case Type.B:
{
string variable = "y";
/* Do other stuff with variable */
}
break;
}
- 3 回答
- 0 关注
- 541 浏览
添加回答
举报
0/150
提交
取消