Variable declaration in a C# switch statement(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 语句中的变量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# switch 语句中的变量声明


- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01