How to create variables with dynamic names in C#?

前端 未结 6 1428
伪装坚强ぢ
伪装坚强ぢ 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 03:08

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

            Dictionary dictionary = new Dictionary();
            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 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
    

提交回复
热议问题