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

查看:24
本文介绍了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?

例如,下面的代码抛出错误A local variable named 'variable' is already defined in this scope".

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天全站免登陆