本文为原创文章、源代码为原创代码,如转载/复制,请在网页/代码处明显位置标明原文名称、作者及网址,谢谢!


开发工具:VS2017

语言:C#

DotNet版本:.Net FrameWork 4.0及以上

一、本文使用的C#语言要点有以下几个:

拓展方法、泛型方法、泛型约束、递归,不懂的可以自行百度

二、具体代码如下:

原始版(不使用SelectMany):

    public static class Ulity
{
public static IEnumerable<T> GetChildControls<T>(this Control control) where T:Control
{
if (control.Controls.Count == ) return Enumerable.Empty<T>();
IEnumerable<T> firstControls = control.Controls.OfType<T>();
IEnumerable<T> secondControls = Enumerable.Empty<T>();
bool theSame = false;
foreach (var item1 in control.Controls)
{
theSame = false;
foreach (var item2 in firstControls)
{
if(item1 == item2)
{
theSame = true;
break;
}
}
if(!theSame)
{
secondControls = secondControls.Concat(GetChildControls<T>((Control)item1));
} }
return firstControls.Concat(secondControls);
}
}

简洁版(使用SelectMany):

    public static class Ulity
{
public static IEnumerable<T> GetChildControls<T>(this Control control) where T:Control
{
if (control.Controls.Count == ) return Enumerable.Empty<T>();
return control.Controls.OfType<T>().Concat(control.Controls.OfType<Control>().SelectMany(GetChildControls<T>));
}
}

三、设计界面如下:

[C#]获得WindowsForm上所有特定类型的控件-LMLPHP

四、运行效果如下:

[C#]获得WindowsForm上所有特定类型的控件-LMLPHP

05-11 11:30
查看更多