1

我有很多Int32要选择的变量int要检查。是否可以制作这条线并使用多变量选择一个变量?

Int32 redleft0 = 0; 
Int32 redleft1 = 0; 
Int32 redleft2 = 0; 
Int32 redleft3 = 0; 
Int32 redleft4 = 0; 
Int32 redleft5 = 0;
Int32 blueleft0 = 0; 
Int32 blueleft1 = 0; 
Int32 blueleft2 = 0; 
Int32 blueleft3 = 0;     
Int32 blueleft4 = 0; 
Int32 blueleft5 = 0;

redorblue = "red";    
for (int i = 0; i < count; i++)
{ 
    String checkleftint = (redorblue + "left" + i);                   
    if (checkleftint < 0)
    {
    }
}
4

4 回答 4

7

你应该在这里使用一个数组——或者更确切地说是两个——:

var red = new int[]{0,0,0,0,0,0};
var blue = new int[]{0,0,0,0,0,0};

var arrayToUse = redorblue == "red" ? red : blue;
for (int i = 0; i < count; i++)
{
    var value = arrayToUse[i];
    // ....
}
于 2013-03-19T13:16:02.990 回答
0

使用带有键和值的数组或字典,以便您可以使用键提取值

于 2013-03-19T13:16:10.443 回答
0

它不会那样工作。要么不使用单独的变量,而是使用数组:

int[,] vars = new int[2,6] { { 0, 0, 0, 0, 0, 0 },  { 0, 0, 0, 0, 0, 0 } };
// int[0,*] would be redleft and int[1,*] would be blueleft

或使用Dictionary<string, int>

于 2013-03-19T13:16:31.593 回答
-1

如果您使用enum是可能的,例如:

enum values { redleft0 = 0; redleft1 = 120; redleft2 = 13; }

通过使用enum

所以你要做的只是:

for (int i = 0; i < count; i++)
{  
   if(i == values.redLeft0){
     ...
   }
} 

通过使用enum,您可以将您想要的名称与您想要的号码相关联。

如果这不是您要的,请澄清。

于 2013-03-19T13:16:43.597 回答