Variables in a loop

前端 未结 9 1508
眼角桃花
眼角桃花 2020-12-19 18:32

I was wondering whether there\'s a way in a \"for\" loop to assign a value to a string variable named according to its index number?

let\'s say I have 3 string varia

9条回答
  •  时光取名叫无心
    2020-12-19 19:11

    You said you don't want to have a switch statement. I realize this does have a switch, but if you must have three different variables, you could encapsulate your switch inside a function call:

    string message1 = null;
    string message2 = null; 
    string message3 = null;
    
    void SetMessage(int i, string value)
    {
        if(i == 1)
            message1 = value;
        etc
    }
    
     for (int i = 1; i <=3; i++)
     {
       SetMessage(i, "blabla" + i.ToString());
     }
    

    Not an optimal solution but if you MUST have separate variables it will hide the mess.

提交回复
热议问题