c# - 如何在 C# 中通过循环组合变量名?

标签 c# winforms loops variables

我重写了这个问题,因为不是每个人都理解。希望没问题,同样是主要问题。非常抱歉

我有一个带有 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/

相关文章:

c++ - 创建一个包含汽车年份和制造商的动态数组但无法保存我的第一个输出

c# - Monotouch/Xamarin 绑定(bind)继承

c# - 如何在派生类中隐藏基类公共(public)属性

c# - 在 Mono 中使用 Microsoft Chart (WinForm)

matlab - 在没有 'fieldnames' 的情况下迭代 MATLAB 中的结构

loops - 可以cl :loop use a custom sum function?

c# - 将 null 传递给泛型方法时,奇怪的是我仍然可以获得类型

c# - Hololens 应用程序将不再构建 - 引用元数据文件丢失且 c-Sharp.firstpass 未找到

c# - 通过引用列名查找列索引?

c# - 在应用程序执行之间保留数据