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 语句中的变量声明


基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01