C# switch 语句中的变量声明

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/222601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 18:47:39  来源:igfitidea点击:

Variable declaration in a C# switch statement

c#switch-statement

提问by Jeremy

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

为什么在C#的switch语句中,对于一个在多种情况下使用的变量,你只在第一种情况下声明?

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

例如,下面的代码抛出错误“一个名为‘variable’的局部变量已经在这个作用域中定义”。

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

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?

但是,根据逻辑,如果类型为 ,则不应命中初始声明Type.B。switch 语句中的所有变量是否都存在于单个作用域中,它们是否在处理任何逻辑之前创建/分配?

采纳答案by Mitchel Sellers

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.

就个人而言,如果您在示例中为开关内的某些内容设置值以使其真正有任何好处,则无论如何您都希望在开关外声明它。

回答by Jon Skeet

Yes, the scope is the entire switch block - unfortunately, IMO. You can always add braces within a single case, however, to create a smaller scope. As for whether they're created/allocated - the stack frame has enough space for all the local variables in a method (leaving aside the complexities of captured variables). It's not like that space is allocated during the method's execution.

是的,范围是整个开关块 - 不幸的是,IMO。但是,您始终可以在单个案例中添加大括号以创建更小的范围。至于它们是否被创建/分配 - 堆栈帧有足够的空间用于方法中的所有局部变量(撇开捕获变量的复杂性)。这不像在方法执行期间分配空间。

回答by itsmatt

Because their scope is at the switch block. The C# Language Specificationstates the following:

因为它们的作用域在 switch 块上。在C#语言规范规定如下:

The scope of a local variable or constant declared in a switch block is the switch block.

在 switch 块中声明的局部变量或常量的作用域是 switch 块。

回答by James Curran

The initialization takes place in the case, but the declaration is effectively done at the top of the scope. (Psuedo-code)

初始化发生在 case 中,但声明实际上是在作用域的顶部完成的。(伪代码)

switch (Type)
{
string variable;

    case Type.A:
            variable = "x";
                break;
    case Type.B:
            variable = "y";
                break;
}

回答by jezell

The variables do share scope in the C# compiler. However, scope doesn't exist in the same way in CIL. As for actual creation / initialization... the .NET memory model lets the compiler move reads / writes a bit as long as simple rules are followed unless the variable is marked as volatile.

这些变量在 C# 编译器中共享作用域。但是,作用域在CIL中并不以相同的方式存在。至于实际的创建/初始化... .NET 内存模型允许编译器稍微移动读取/写入,只要遵循简单的规则,除非变量被标记为volatile

回答by Michael Burr

If you want a variable scoped to a particular case, simply enclose the case in its own block:

如果你想要一个作用域为特定情况的变量,只需将该情况包含在它自己的块中:

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;
}

回答by percebus

"In My Daaaaays..."

“在我的天啊……”

swicthis a really primitive procedural implementation that has been around since the ages of Citself (even before C++).

swicth是一个非常原始的过程实现,它自其时代以来就已经存在C(甚至在 之前C++)。

The whole switchis a blockthat serves as a scope-contained GOTO:(hence the :in each case). If you took some assembler classes, that might seem familiar.

整体switch是一个,用作范围包含GOTO:(因此:在 each case)。如果您参加了一些汇编课程,那可能看起来很熟悉。

That is why switchuse is most helpful when combining with Enums and not using breakin every single caselike

这就是为什么switchuse 在与Enums结合而不是break在每个caselike 中使用时最有用

switch(mood)
{
    case Mood.BORED:
    case Mood.HAPPY:
        drink(oBeer) // will drink if bored OR happy
break;

    case Mood.SAD: // unnecessary but proofs a concept
    default:
        drink(oCoffee)
break;
}