How to create variables with dynamic names in C#?

前端 未结 6 1424
伪装坚强ぢ
伪装坚强ぢ 2021-01-25 02:29

I want to create a var in a for loop, e.g.

for(int i; i<=10;i++)
{
    string s+i = \"abc\";
}

This should create variables s0, s1, s2... to

相关标签:
6条回答
  • 2021-01-25 02:53

    You probably want to use an array. I don't know exactly how they work in c# (I'm a Java man), but something like this should do it:

    string[] s = new string[10];
    for (int i; i< 10; i++)
    {
        s[i] = "abc";
    }
    

    And read http://msdn.microsoft.com/en-us/library/aa288453(VS.71).aspx

    0 讨论(0)
  • 2021-01-25 03:04

    Your first example wouldn't work in any language as you are trying to redefine the variable "i". It's an int in the loop control, but a string in the body of the loop.

    Based on your updated question the easiest solution is to use an array (in C#):

    string[] s = new string[10];
    for (int i; i< 10; i++)
    {
        s[i] = "abc";
    }
    
    0 讨论(0)
  • 2021-01-25 03:05

    This depends on the language.

    Commonly when people want to do this, the correct thing is to use a data structure such as a hash table / dictionary / map that stores key names and associated values.

    0 讨论(0)
  • 2021-01-25 03:08

    You may use dictionary. Key - dynamic name of object Value - object

            Dictionary<String, Object> dictionary = new Dictionary<String, Object>();
            for (int i = 0; i <= 10; i++)
            {
                //create name
                string name = String.Format("s{0}", i);
                //check name
                if (dictionary.ContainsKey(name))
                {
                    dictionary[name] = i.ToString();
                }
                else
                {
                    dictionary.Add(name, i.ToString());
                }
            }
            //Simple test
            foreach (KeyValuePair<String, Object> kvp in dictionary)
            {
                Console.WriteLine(String.Format("Key: {0} - Value: {1}", kvp.Key, kvp.Value));
            }
    

    Output:

    Key: s0 - Value: 0
    Key: s1 - Value: 1
    Key: s2 - Value: 2
    Key: s3 - Value: 3 
    Key: s4 - Value: 4
    Key: s5 - Value: 5
    Key: s6 - Value: 6
    Key: s7 - Value: 7
    Key: s8 - Value: 8
    Key: s9 - Value: 9
    Key: s10 - Value: 10
    
    0 讨论(0)
  • 2021-01-25 03:09

    Obviously, this is highly dependent on the language. In most languages, it's flat-out impossible. In Javascript, in a browser, the following works:

    for (var i = 0; i<10 ; i++) { window["sq"+i] = i * i; }
    

    Now the variable sq3, for example, is set to 9.

    0 讨论(0)
  • 2021-01-25 03:15

    Use some sort of eval if it is available in the language.

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