代码之家  ›  专栏  ›  技术社区  ›  yeeen

是否可以循环访问变量列表,名称只因数字不同而不同?

  •  0
  • yeeen  · 技术社区  · 14 年前

    例如,在Windows窗体中,文本框textbox 0到textbox 29,需要将它们全部分配给一个数组。我现在能想到的是这样做:

    array[0] = textbox0;
    array[1] = textbox1;
    ...
    array[29] = textbox29;
    

    我是否可以这样做:

    for(int i=0; i<30; i++)
    {
        array[i] = textbox + i; 
        //and some magic is done such tt this is a variable, eg. textbox1
    }
    
    4 回复  |  直到 6 年前
        1
  •  1
  •   sh_kamalh    14 年前

    我正在修改@rdkleine代码

    Control[] array = new Control[100];
    foreach (Control c in FormX.Controls)
    {
        int index;
        if (c.Name.StartsWith("textbox") && int.TryParse(c.Name.Substring(7),out index))
        {
            array[index] = c;
        }
    }
    

    我认为这应该将控件放在数组中的正确索引中。

        2
  •  5
  •   Nick Jones    14 年前
    this.Controls.OfType<TextBox>().ToArray()
    

    应该有效。它选择文本框控件,然后将其转换为数组。

        3
  •  4
  •   Ralf de Kleine    14 年前

    从我的头顶:

    int i = 0;
    foreach (Control c in FormX.Controls)
    {
        int i2;
        if (c.Name.StartsWith("textbox") && int.TryParse(c.Name.Substring(7),out i2))
        {
            array[i] = c;
            i++;
        }
    }
    array = array.OrderBy(a => Convert.ToInt32(a.Name.Substring(7))).ToArray();
    
        4
  •  2
  •   Jon Skeet    14 年前

    好吧,你 能够 使用反射…但就我个人而言,我会尽量避免创建所有这些单独的变量。例如,如果你 真正地 需要设计器支持,可以避免创建单独的变量,但通过按名称查找控件来创建数组。

    或者,如果您可以在循环中以编程方式自动生成控件,我会这样做。