1

我正在尝试使用从字符串派生的复选框名称填充复选框数组。我想替换以下代码:

    public void CheckBox_1()
    {
        CheckBox[] boxes_1 = new CheckBox[4];

        boxes_1[0] = A0;
        boxes_1[1] = A1;
        boxes_1[2] = A2;
        boxes_1[3] = A3;

        for (int i = 0;i < 4;i++)   
        {
            boxes_1[i].Enabled = checkBox1.Checked == true ? true : false;
        }
    }

像这样:

    public void CheckBox_1()
    {
        CheckBox[] boxes_1 = new CheckBox[4];

        for (int i = 0; i < 4; i++)
        {
            boxes_1[i] = ("A" + i);
        }

        for (int i = 0; i < 4; i++)
        {
            boxes_1[i].Enabled = checkBox1.Checked == true ? true : false;
        }
    }

我可以很容易地将复选框名称转换为字符串,但尚不清楚如何完成此操作。谢谢。

4

3 回答 3

1

您可以使用包含对象的Control.Controls来获取所有CheckBox控件OfType<T>,然后过滤Name以“A”开头的 s。

var container = ...control with the checkboxes...;

foreach(var cb in container.Controls.OfType<CheckBox>().Where(c => c.Name.StartsWith("A")))
{
   cb.Enabled = checkBox1.Checked;
}
于 2012-06-08T14:54:13.033 回答
0

我建议不要为了创建容易出错且难以理解的代码而摆弄反射,而是建议将相关复选框分组到容器控件中,例如GroupBox.

然后它非常简单易读:

// consider renaming
public void CheckBox_1()
{
    var relatedCheckBoxes = GroupBox1.Controls.OfType<CheckBox>();
    foreach (var chk in relatedCheckBoxes)
        chk.Enabled = checkBox1.Checked; // you might want to pass this checkbox as argument instead
}
于 2012-06-08T14:54:40.323 回答
0

假设复选框可以嵌套在某个公共容器内的其他控件中,这可能会起作用:

    private void CheckBox_1()
    {
        foreach (var checkbox in FindChildren<CheckBox>(container, c => c.Name.StartsWith("A")))
        {
            checkbox.Enabled = checkBox1.Checked == true ? true : false;
        }
    }

    public static IEnumerable<T> FindChildren<T>(Control parent, Func<T, bool> filter)
        where T : Control
    {
        var search = new Stack<Control>();
        search.Push(parent);

        while (search.Count > 0)
        {
            parent = search.Pop();

            foreach (Control child in parent.Controls)
            {
                T typed = child as T;

                if (typed != null && filter(typed))
                {
                    yield return typed;
                    continue;
                }

                search.Push(child);
            }
        }
    }
于 2012-06-08T15:05:40.453 回答