【问题标题】:Access variable's value via its string name C#通过字符串名称访问变量的值 C#
【发布时间】:2016-08-24 21:20:20
【问题描述】:

我想将一系列(准确地说是六个)Windows 窗体标签存储在一个数组中。有六个标签,遵循命名约定orderLabel0orderLabel1...orderLabel5

我想将指向 orderLabels 的指针存储在一个数组中:

Label[] orderLabels = new Label[6];
for(int index = 0; index < 6; index++)
{                
    orderLabels[index] = orderLabel + [index]; //Error!
}

代码需要以某种方式将字符串视为变量名并将它们存储为“标签”而不是 orderLabels 数组中的字符串。也就是说,当orderLabels[0]被访问时,我实际上是在访问orderLabel0

在这里和那里的研究使我找到了dynamicReflectionDictionary 选项。但是,它们都要求我指定对象名称(如果我错了,请纠正我),并且我试图遵循“不要重复”自己的规则,不必指定对象六次。

请指教,谢谢。

【问题讨论】:

  • 创建一个哈希图...我觉得很有趣,如果我用谷歌搜索这些问题中的大多数,我会得到一个堆栈溢出问题的答案。 stackoverflow.com/questions/1293549/string-to-variable-name
  • 子控件已经存储在父容器Controls属性中
  • 您的表单中是否已经存在orderLabel0orderLabel5
  • 嗨 Reza 和 Seany84,是的。
  • 看看this post。您可以简单地使用他们的名字找到他们。您需要在循环中使用的名称是string.Format("orderLabel{0}", index)

标签: c# winforms


【解决方案1】:

您可以使用Controls 表单变量按名称查找控件:

Label[] orderLabels = new Label[6];
for(int index = 0; index < 6; index++)
{                
    orderLabels[index] = Controls[string.Format("orderLabel{0}", index)] as Label;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-02
    • 2021-07-05
    • 1970-01-01
    • 2023-01-09
    • 1970-01-01
    • 1970-01-01
    • 2018-10-20
    • 2011-02-24
    相关资源
    最近更新 更多