简体   繁体   English

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

[英]Access variable's value via its string name C#

I want to store a series (six to be precise) of Windows Forms labels in an array. 我想将一系列(准确地说是六个)Windows窗体标签存储在一个数组中。 There are six labels, which follow the naming convention orderLabel0 , orderLabel1 ... orderLabel5 . 有六个标签,遵循命名约定orderLabel0orderLabel1 ... orderLabel5

I would like to store the pointers to the orderLabels in an array: 我想将指向orderLabels的指针存储在数组中:

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

The code somehow needs to treat the string as variable name and store them as "labels" rather than string in the orderLabels array. 代码需要以某种方式将字符串视为变量名,并将其存储为“标签”,而不是orderLabels数组中的字符串。 In other words, when orderLabels[0] is accessed, I am actually accessing orderLabel0 . 换句话说,当访问orderLabels[0]时,实际上是在访问orderLabel0

Research here and there have led me to dynamic , Reflection and Dictionary options. 各地的研究使我想到了dynamicReflectionDictionary选项。 However, they all require me to specify the object names (correct me if I am wrong), and I am trying to follow the "Do Not Repeat" yourself rule by not having to specify the object six times. 但是,它们都要求我指定对象名称(如果我错了,请更正我),并且我试图遵循自己的“请勿重复”规则,不必重复指定对象六次。

Please advise, thank you. 请指教,谢谢。

You can use the Controls form variable to look up the control by name: 您可以使用Controls表单变量按名称查找控件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM