通过字符串名称C#访问变量的值

时间:2016-08-24 21:20:21

标签: c# winforms

我想在一个数组中存储一系列(确切地说是六个)Windows窗体标签。共有六个标签符合命名惯例orderLabel0orderLabel1 ... orderLabel5

我想将指针存储到数组中的orderLabels:

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

代码以某种方式将字符串视为变量名称并将其存储为&#34;标签&#34;而不是orderLabels数组中的字符串。换句话说,当访问orderLabels[0]时,我实际上正在访问orderLabel0

此处的研究让我了解dynamicReflectionDictionary个选项。但是,它们都要求我指定对象名称(如果我错了,请纠正我),并且我正在尝试遵循&#34;不要重复&#34;你自己统治六次不必指定对象。

请告知,谢谢。

1 个答案:

答案 0 :(得分:2)

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

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