如何通过C#中的循环来组成变量名称? [英] How can I compose variables names through loop in C#?
问题描述
我已经重写了这个问题,因为不是每个人都理解.希望可以,这是相同的主要问题.非常抱歉
我有一个带有15个进度条的winform,它们分别是:"baraClasa1","baraClasa2","baraClasa3" ..."baraClasa15".我必须从一些数据库记录中为所有这些属性分配.VALUE属性(如 int ).(记录访问不同时间段的不同值)我在想,也许可以通过执行以下操作来使用循环为所有对象分配.Value属性:
for(int i = 0; i< value; i ++){"baraClasa + i".值= 20 + i;}
是否可以像这样组成变量的名称?
我对字典,列表了解不多,但一直在研究.如果没有任何效果,那就去做丑陋的事情:
int值= 20;baraClasa1 =值;baraClasa2 =值+1; ....
谢谢您的帮助
您必须进行一些反思.
公共字符串variable0,variable1,variable2,variable3,variable4,variable5;private void button1_Click(对象发送者,EventArgs e){对于(int i = 0; i< 6; i ++){//假装我的变量名是variable1,variable2 ..("variable"不是数组!只是"assign"变量)System.Reflection.FieldInfo info = this.GetType().GetField("variable" + i.ToString());//将测试"替换为所需的值,例如分配[i]info.SetValue(this,"testing");}//用您的新值做些事}
在更新的问题上无需使用反射.控件集合具有内置的查找功能,可通过名称字符串获取控件.
for(int i = 0; i< 6; i ++){ProgressBar bar =(ProgressBar)this.Controls ["baraClasa" + i.ToString()];bar.Value = 50;}
I have rewritten this question because not everyone understood. Hope it's ok, it's the same main problem.Very sorry
I have a winform with 15 progress bars called: "baraClasa1", "baraClasa2", "baraClasa3" ... "baraClasa15". I have to assign the .VALUE property (as in int) to all of them, from some database records. (The records access the different values from different time periods) I was thinking that maybe it is possible to use a loop to assign the .Value property to all of them by doing something like:
for(int i=0; i<value; i++)
{
"baraClasa+i".Value = 20 + i;
}
Is it possible to compose the name of the variables like that?
I don't know much about dictionaries, lists but looking into. If nothing works il just do the ugly:
int value = 20;
baraClasa1 = value;
baraClasa2 = value +1;....
Thank you for all help
You have to do a little reflection.
public string variable0, variable1, variable2, variable3, variable4, variable5;
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 6; i++)
{
//pretending my variable names are variable1, variable2.. ("variable" is NOT an array! just the "assign" variable)
System.Reflection.FieldInfo info = this.GetType().GetField("variable" + i.ToString());
// replace "testing" with the value you want e.g. assign[i]
info.SetValue(this, "testing");
}
// Do something with your new values
}
No need to use reflection with the updated question. The control collection has a built in find for getting a control by the name string.
for (int i = 0; i < 6; i++)
{
ProgressBar bar = (ProgressBar)this.Controls["baraClasa" + i.ToString()];
bar.Value = 50;
}
这篇关于如何通过C#中的循环来组成变量名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!