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

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

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

但是,如果我使用“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; } 

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

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

我使用Visual Studio 2010。

谢谢

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

在块{ }内声明的任何变量仅在该块中可见。 块之后的任何代码都无法看到它。 因此,你的ifusing组件代码声明了变量,但它在这两个分支中这样做,所以后来的代码根本看不到它。

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

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

它仍然具有相同的范围问题,因为该变量在switch块外部不可见。 同样,解决方案是首先声明变量,然后在switch内分配它。

您已在if的范围内声明了数组,但您想从外部访问它。 这不起作用。 你必须在外面宣布它。 但是你不能使用集合初始化器语法:

 int x; x=1; string[,] arraySpielfeld2d = new string[2,2]; if (x == 1) { arraySpielfeld2d[0,0] = "1"; arraySpielfeld2d[0,1] = "1"; arraySpielfeld2d[1,0] = "1"; arraySpielfeld2d[1,1] = "1"; } else if(x == 2) { arraySpielfeld2d[0, 0] = "2"; arraySpielfeld2d[0, 1] = "2"; arraySpielfeld2d[1, 0] = "2"; arraySpielfeld2d[1, 1] = "2"; } MessageBox.Show(arraySpielfeld2d[0,0]); 

对于如果使用大括号( { } )也会创建新范围的switch也是如此。

请注意,在这种情况下你不需要ifswitch ,似乎你总是想要使用x

 string val = x.ToString(); string[,] arraySpielfeld2d = { {val, val }, {val, val } }; 

if/elseswitch范围之外声明arraySpielfeld2d然后你可以在if/else和inside switch之外访问它

这是你的代码应该如何开始,基本上你在if-then-else中锁定了变量的范围,它需要在括号外声明。

 int x; x=1; // define variable OUTSIDE of the if-then-else scope string[,] arraySpielfeld2; or string[2,2] arraySpielfeld2 = new string[2,2](); if (x==1) { // assign the variable here if you create it then scope is // restricted to the code between if-then-else // unlike javascript you can't define a global // variable here (by leaving off the var part) arraySpielfeld2d = ... snipped }