[英]How to declare a different variable for every value in a collection in C#?
我想遍歷一個列表,並為列表中的每個值聲明整數變量。
范例:
List<string> VariableNames= new List<string>()
{
"length",
"breadth",
"height"
};
輸出:
int length;
int breadth;
int height;
這可能嗎 ?
Eric J.給出了很好的答案,但是如果您仍然想要列表,則可以執行以下操作:
List<string> variableNames = new List<string>()
{
"length",
"breadth",
"height"
};
Dictionary<string,int> names = variableNames.ToDictionary(name => name, integer => 0);
但是這里您沒有生成變量,每個variableName
(key)都被賦予一個整數值,該整數值被初始化為0,並且您可以使用以下方式訪問該值:
names["height"] //returns the integer variable associated with that string.
沒有代碼生成,您將無法做到這一點。 但是,您可以通過使用字典來解決問題。
Dictionary<string, int> names = new Dictionary<string, int>()
{
{ "length", 0 },
{ "breadth", 0 },
{ "height", 0 },
};
然后,您可以執行類似的操作
names["length"] = 42;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.