且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用模式按名称查找 Windows 窗体控件

更新时间:2023-12-06 09:09:28

您可以通过以下方式使用 LINQ 搜索它们:

You could search for them with LINQ via:

var matches = control.Controls.Cast<Control>()
                     .Where(c => c.Name.StartsWith("btnOverlay"));

Cast 调用是必需的,因为 ControlCollection 没有实现 IEnumerable,只有 IEnumerable代码>.此外,这不会进行递归搜索,而只会直接搜索包含的控件.如果需要递归,您可能需要将其重构为 类似于这个答案的方法.

The Cast<T> call is required, as ControlCollection does not implement IEnumerable<T>, only IEnumerable. Also, this doesn't do a recursive search, but only searches the contained controls directly. If recursion is required, you'll likely need to refactor this into a method similar to this answer.