【问题标题】:Create variable which will be named with listValue创建将以 listValue 命名的变量
【发布时间】:2016-10-09 03:01:58
【问题描述】:

我在创建将由列表值命名的变量时遇到了一点问题。

这是我想要的示例。

for (int i = 0; i < list.Count; i++)
{
  //here I want to create variable
  //which will be named with list[i]
}

所以如果列表有 2 个元素,例如。

list[0] = "testName"
list[1] = "andAnotherOne"

我想创建 2 个变量, 其中一个名为 testName,第二个名为 andAnotherOne

你能帮我完成吗?

【问题讨论】:

  • 这在 C# 中是不可能的。您的下一个最佳方法是字典。然后,您可以通过字符串键访问这些值。但是变量必须要有名字才能编译。
  • 如果你想存储 Key&Value 去字典。否则这是荒谬的,因为编译后变量将具有完全不同的名称。
  • 编译后变量名会完全不同。嗯。没有after,因为没有before,因为根本写不出来。
  • @TaW 是的,你是对的。运行时不会创建变量,现有变量会在编译期间重命名。

标签: c#


【解决方案1】:

正如 TaW 所说,我相信您需要 Dictionary。这使您可以拥有与索引相同的值。

Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("foo","foo"); //index,value of index
if(dictionary.ContainsKey["foo"])
{ 
    string value = dictionary["foo"];
    Console.Write(value);
}

希望我能理解你的问题。

【讨论】:

  • 什么意思?我是新手,有没有回答问题的礼仪?有的话抱歉。另外,我不完全理解他的要求。所以我做了一个通用的例子
  • 你的回答很好。我的意思是,因为他发布了带有名称列表的代码,您可以使用它来创建条目..
【解决方案2】:

只需创建一个List&lt;string&gt; names = new List&lt;string&gt;();

   for (int i = 0; i < 5; i++)
   {
      names.Add("sample" + i);
   }

编辑:

如果您想引用名称,请使用如下字典,

Dictionary<string, string> myvalues = new Dictionary<string, string>();

【讨论】:

  • 这有什么帮助?可能是字典,但他想将名称与值相关联,而不仅仅是索引。
  • 但第二部分将 list[0] 和 list[1] 作为值
【解决方案3】:

您可以使用dynamicExpandoObject

var variables = new List<string> { "variableOne", "variableTwo" };

dynamic scope = new ExpandoObject();

var dictionary = (IDictionary<string, object>)scope;

foreach (var variable in variables)
    dictionary.Add(variable, "initial variable value");

Console.WriteLine(scope.variableOne);
Console.WriteLine(scope.variableTwo);

【讨论】:

    【解决方案4】:

    在 C# 中,变量都是静态声明的。我认为你不能那样做。也许你可以尝试使用反射,但我认为它不能让你做你想做的事。

    我发现的一些你可能感兴趣的东西:

    string to variable name

    Convert string to variable name

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-07
      • 2017-07-11
      • 2014-02-24
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多