C#:使用 if/switch 时出错:“本地变量已在此范围内定义”

Spa*_*ker 3 c# arrays

我是 C# 新手,我的问题可能很简单,但我不明白:

我需要根据条件为数组分配一些值。所以我可以使用“switch”语句的“if”来检查条件。

但是,如果我使用“switch”,则会收到错误“本地变量已在此范围中定义”。

如果我使用“if”,那么我会收到一个错误“在当前上下文中不存在”

例子:

int x;
x=1;

//1:
//a)  does work...
if (x==1)
{
        string[,] arraySpielfeld2d = 
        {
         {"1", "1" },
         {"1", "1" }
        };
}
else
{
        string[,] arraySpielfeld2d = 
        {
         {"1", "1" },
         {"1", "1" }
        };
}


//b) but this does not work
MessageBox.Show(arraySpielfeld2d[0,0]);  //error: does not exist in current context


//2) doesn't work at all
switch (x)
    {

    case 1:
        string[,] arraySpielfeld2d = 
        {
         {"1", "1" },
         {"1", "1" }
        };
        break;


    case 2:
        string[,] arraySpielfeld2d =    //error:Local variable already defined in this scope
        {
         {"2", "2" },
         {"2", "2" }
        };
        break;

    }
Run Code Online (Sandbox Code Playgroud)

所以使用“if”我至少可以填充数组(1a)......但我无法访问数组元素(1b)......使用“switch”根本不起作用。

那么如何根据条件(if/switch)分配然后访问数组的值呢?

我使用 Visual Studio 2010。

谢谢

Mat*_*ton 5

您在这里遇到的是变量的范围

在块{ }内声明的任何变量仅在该块内可见。块之后的任何代码都将无法看到它。因此,您的if-using 代码声明了该变量,但它是在这两个分支中声明的,因此之后的代码根本看不到它。

解决方案是在 之前声明变量if,在块中分配它,然后您可以在之后使用它(只要确保您没有留下最终未分配的路径,除非您为这种可能性做好了准备)用它)。

switch代码不起作用,因为整个语句只有一个块,并且您在其中声明了两次相同的变量名。

尽管如此,它仍然存在相同的范围问题,因为该变量在switch块外不可见。同样,解决方案是先声明变量,然后在switch.