从字符串中填充复选框数组名称
本文关键字:数组 复选框 填充 字符串 | 更新日期: 2023-09-27 18:36:31
我正在尝试用从字符串派生的复选框名称填充复选框数组。我想替换以下代码:
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;
}
}
我可以很容易地将复选框名称转换为字符串,但不清楚如何完成此操作。谢谢。
您可以使用包含对象的 Control.Controls 通过 OfType<T>
获取所有CheckBox
控件,然后筛选以"A"开头的Name
。
var container = ...control with the checkboxes...;
foreach(var cb in container.Controls.OfType<CheckBox>().Where(c => c.Name.StartsWith("A")))
{
cb.Enabled = checkBox1.Checked;
}
与其摆
弄反射只是为了创建容易出错且难以理解的代码,我建议将相关复选框分组在容器控件中,例如 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
}
假设复选框可以嵌套在某个常见容器内的其他控件中,这可能有效:
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);
}
}
}