C#:使用错误,如果/开关:"局部变量已经在这个范围与定义QUOT; [英] C# : error using if/switch : "Local variable already defined in this scope"
问题描述
我是新的C#和我的问题可能是简单的,但我不明白这一点:
I'm new to C# and my problem is probably simple, but I don't get it:
我需要一些值分配给根据条件的阵列。
所以,我可以使用开关语句的如果检查的条件。
I need to assign some values to an array depending on a condition. So I can use "if" of "switch" statement for checking the condition.
不过,如果我用切换然后我得到一个错误在此范围内已定义的局部变量。
However,if I use "switch" then I get an error "Local variable already defined in this scope".
如果我用如果,那么我得到一个错误并不在目前的情况下存在
And if I use "if" then I get an error "does not exist in current context"
例如:
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;
}
因此,使用如果我至少可以填充阵列(1A)...但我不能访问数组元素(1B)...
使用开关不工作的。
So using "if" I can at least populate the array (1a)...but I can not access the array elements (1b)... Using "switch" doesn't work at all.
所以,我怎么能和分配可以根据条件,然后到一个数组访问值(如果/开关)?
So how could I assign and then access values to an array depending on a condition (if/switch)?
我使用Visual Studio 2010。
I use Visual Studio 2010.
感谢
推荐答案
您已经宣布的范围阵列的如果
,但你想从外部访问。这是行不通的。你必须在外面声明。但你不能使用集合初始化语法:
You have declared the array in the scope of the if
, but you want to access it from outside. That doesn't work. You have to declare it outside. But then you can't use the collection initializer syntax:
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]);
同样是一个开关
如果你使用括号( {}
),这也创造了一个新的作用域真
The same is true for a switch
which also creates a new scope if you use braces({ }
).
请注意,您不需要在这种情况下,如果
或开关
,似乎你总是希望使用 X
:
Note that you don't need an if
or switch
in this case, it seems that you always want to use x
:
string val = x.ToString();
string[,] arraySpielfeld2d =
{
{val, val },
{val, val }
};
这篇关于C#:使用错误,如果/开关:"局部变量已经在这个范围与定义QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!