繁体   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