简体   繁体   中英

Select an variable using multi variables

I have a lot of Int32 variables that I wanted to select which int I want to check. Is it possible to make this line and select an variable using multi variables?

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)
    {
    }
}

You should use an array - or rather two - here:

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];
    // ....
}

将数组或字典与键和值一起使用,以便可以使用键提取值

It won't work that way. Either don't use separate variables but use an array:

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

or use a Dictionary<string, int>

It's possible if you use enum , for example:

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

By using enum

So what you wolud do is just:

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

By using enum , you associate a name you want to a number you want.

If this is not what you're asking for, please clarify.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM