Variables in a loop

前端 未结 9 1394
眼角桃花
眼角桃花 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 18:56

    You can't do that (well, not sanely). Have you considered using an array of strings instead?

    0 讨论(0)
  • 2020-12-19 19:01

    Usually instead of having N differents variables named 1, 2, ..., N the way is to store them in an array:

    string message[3];
    message[0] = null;
    message[1] = null;
    message[2] = null; 
    

    and then the loop:

    for (int i = 0; i <=2; i++)  
    {  
       message[i] = "blabla" + i.ToString();  
    }  
    

    Note that, usually again, a set of indexed variables starts with value 0 ;)

    0 讨论(0)
  • 2020-12-19 19:09

    I think you should use an array for this kind of variables.

    string[] message = new string[3];
    for (int i = 1; i <=3; i++)
    {
         message[i] = "blabla" + i.ToString();
    }
    
    0 讨论(0)
  • 2020-12-19 19:09

    You can also do it without the index:

        string[] Messages = { "Tom", "Dick", "Harry" };
    
        foreach (String Message in Messages)
        {
            Response.Write("Hello " + Message + "<br />");
        }
    
    0 讨论(0)
  • 2020-12-19 19:10

    can you use an array? or list type?

    string[] messages = new string[3];
    for (int i = 1; i <=3; i++)
     {
       messages[i] = "blabla" + i.ToString();
     }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题