更新时间:2023-12-06 09:09:34
这里有另一种选择.我通过创建一个示例应用程序对其进行了测试,然后将一个 GroupBox 和一个 GroupBox 放在初始 GroupBox 中.在嵌套的 GroupBox 中,我放置了 3 个 TextBox 控件和一个按钮.这是我使用的代码(甚至包括您正在寻找的递归)
Here's another option for you. I tested it by creating a sample application, I then put a GroupBox and a GroupBox inside the initial GroupBox. Inside the nested GroupBox I put 3 TextBox controls and a button. This is the code I used (even includes the recursion you were looking for)
public IEnumerable<Control> GetAll(Control control,Type type)
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetAll(ctrl,type))
.Concat(controls)
.Where(c => c.GetType() == type);
}
为了在表单加载事件中对其进行测试,我想要对初始 GroupBox 内的所有控件进行计数
To test it in the form load event I wanted a count of all controls inside the initial GroupBox
private void Form1_Load(object sender, EventArgs e)
{
var c = GetAll(this,typeof(TextBox));
MessageBox.Show("Total Controls: " + c.Count());
}
它每次都返回正确的计数,所以我认为这非常适合您正在寻找的内容:)
And it returned the proper count each time, so I think this will work perfectly for what you're looking for :)