我重写了这个问题,因为不是每个人都理解。希望没问题,同样是主要问题。非常抱歉
我有一个带有 15 个进度条的 winform,名为:“baraClasa1”、“baraClasa2”、“baraClasa3”...“baraClasa15”。我必须从一些数据库记录中将 .VALUE 属性(如 int)分配给所有这些属性。 (记录访问不同时间段的不同值) 我在想也许可以使用循环将 .Value 属性分配给所有这些属性,方法如下:
for(int i=0; i<value; i++)
{
"baraClasa+i".Value = 20 + i;
}
变量名可以这样写吗?
我对字典、列表了解不多,但正在研究。如果什么都不管用,我就做丑陋的:
int value = 20;
baraClasa1 = value;
baraClasa2 = value +1;....
谢谢大家的帮助
最佳答案
你必须做一点反射(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
}
无需对更新后的问题使用反射。控件集合有一个内置的查找功能,用于通过名称字符串获取控件。
for (int i = 0; i < 6; i++)
{
ProgressBar bar = (ProgressBar)this.Controls["baraClasa" + i.ToString()];
bar.Value = 50;
}
关于c# - 如何在 C# 中通过循环组合变量名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20908385/