如何在 C# 中创建具有动态名称的变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1147967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create variables with dynamic names in C#?
提问by cagin
I want to create a var in a for loop, e.g.
我想在 for 循环中创建一个 var,例如
for(int i; i<=10;i++)
{
string s+i = "abc";
}
This should create variables s0, s1, s2... to s10.
这应该创建变量 s0、s1、s2... 到 s10。
回答by ChrisF
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.
当您尝试重新定义变量“i”时,您的第一个示例不适用于任何语言。它是一个int
在循环控制中,但string
在循环体中。
Based on your updated question the easiest solution is to use an array (in C#):
根据您更新的问题,最简单的解决方案是使用数组(在 C# 中):
string[] s = new string[10];
for (int i; i< 10; i++)
{
s[i] = "abc";
}
回答by Alan Haggai Alavi
Use some sort of eval
if it is available in the language.
使用某种eval
语言,如果它在语言中可用。
回答by Jason Kresowaty
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.
通常当人们想要这样做时,正确的做法是使用存储键名称和关联值的数据结构,例如哈希表/字典/映射。
回答by Jason Kresowaty
Obviously, this is highly dependent on the language. In most languages, it's flat-out impossible. In Javascript, in a browser, the following works:
显然,这高度依赖于语言。在大多数语言中,这是完全不可能的。在 Javascript 中,在浏览器中,以下工作:
for (var i = 0; i<10 ; i++) { window["sq"+i] = i * i; }
Now the variable sq3, for example, is set to 9.
例如,现在变量 sq3 设置为 9。
回答by Frans
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:
您可能想要使用数组。我不知道它们在 c# 中是如何工作的(我是一个 Java 人),但应该这样做:
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
并阅读 http://msdn.microsoft.com/en-us/library/aa288453(VS.71).aspx
回答by Micha? Ziober
You may use dictionary. Key - dynamic name of object Value - object
你可以使用字典。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));
}
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