1

我想在 for 循环中创建一个 var,例如

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

这应该创建变量 s0、s1、s2... 到 s10。

4

6 回答 6

11

您可能想使用数组。我不确切知道它们在 c# 中是如何工作的(我是一个 Java 人),但是应该这样做:

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

并阅读 http://msdn.microsoft.com/en-us/library/aa288453(VS.71).aspx

于 2009-07-18T16:46:45.077 回答
4

当您尝试重新定义变量“i”时,您的第一个示例不适用于任何语言。它是一个int循环控制,但string在循环体中。

根据您更新的问题,最简单的解决方案是使用数组(在 C# 中):

string[] s = new string[10];
for (int i; i< 10; i++)
{
    s[i] = "abc";
}
于 2009-07-18T16:41:02.607 回答
3

显然,这高度依赖于语言。在大多数语言中,这是完全不可能的。在 Javascript 中,在浏览器中,以下工作:

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

例如,现在变量 sq3 设置为 9。

于 2009-07-18T16:41:42.747 回答
3

你可以使用字典。Key - 对象的动态名称 Value - 对象

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

输出:

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
于 2009-07-18T17:45:43.803 回答
0

eval如果它在该语言中可用,请使用某种。

于 2009-07-18T16:41:12.560 回答
0

这取决于语言。

通常当人们想要这样做时,正确的做法是使用存储键名和关联值的数据结构,例如哈希表/字典/映射。

于 2009-07-18T16:41:36.413 回答