簡體   English   中英

如何使用C#基於列表動態創建變量?

[英]How to Create Variables Dynamically Based on List using C#?

這是我的密碼

Public List<string> Values{get;set;}

在上面的列表中包含多個值。 例如[[10“,” 20“,” 30“]。 我想在c#.net中使用列表值(a =“ 10”,b =“ 20”,c =“ 30”)創建三個變量。 如果列表計數為零,則無需創建變量。

您可以嘗試使用ExpandoObject

  using System.Dynamic;

  ...

  List<string> Values = new List<string>() {
    "10", "20", "30"
  };

  ...

  dynamic variables = new ExpandoObject();

  for (int i = 0; i < Values.Count; ++i)
    (variables as IDictionary<String, Object>).Add(
       ((char) ('a' + i)).ToString(), 
       Values[i]);

  ...

  // 10
  Console.Write(variables.a);

我希望這能幫到您。

if (Values.Count != 0){   
    Dictionary<string, string> dictionary =
            new Dictionary<string, string>();
    char key = 'a';
    for (i = 0; i < Values.Count; i++){
        dictionary.Add(key, Values[i]);
        key = (key == 'z'? 'a': (char)(input + 1));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM