在C#中switch语句变量声明 [英] Variable declaration in a C# switch statement

查看:286
本文介绍了在C#中switch语句变量声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么是它在C#switch语句,在多个案件中使用的变量,你只在第一种情况下申报呢?

Why is it that in a C# switch statement, for a variable used in multiple cases, you only declare it in the first case?

例如,下面抛出错误名为'变'已在此范围内定义的局部变量。

For example, the following throws the error "A local variable named 'variable' is already defined in this scope".

switch (Type)
{
    case Type.A:
            string variable = "x";
                break;
    case Type.B:
            string variable = "y";
                break;
}

但是,每逻辑,初始宣言不应如果类型是 Type.B 击中。做一个switch语句中的所有变量存在于一个单一的范围内,并且他们创造/处理任何逻辑之前分配的?

However, per the logic, the initial declaration should not be hit if the type is Type.B. Do all variables within a switch statement exist in a single scope, and are they created/allocated before any logic is processed?

推荐答案

我相信这与变量的总体范围的事,这是在交换机级别定义的块级范围。

I believe it has to do with the overall scope of the variable, it is a block level scope that is defined at the switch level.

个人如果你是一个值开关内部在你的榜样设置打抱不平,真正有任何好处,你会想反正声明它的开关之外。

Personally if you are setting a value to something inside a switch in your example for it to really be of any benefit, you would want to declare it outside the switch anyway.

这篇关于在C#中switch语句变量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆