• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Dreama
只想要简简单单的快乐!
博客园    首页    新随笔    联系   管理     
[C#]获得WindowsForm上所有特定类型的控件

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


开发工具: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 == 0) 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 == 0) return Enumerable.Empty<T>();
            return control.Controls.OfType<T>().Concat(control.Controls.OfType<Control>().SelectMany(GetChildControls<T>));
        }
    }

三、设计界面如下:

四、运行效果如下:

posted on 2017-12-14 16:10  Dreamma  阅读(719)  评论(1)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3

© 本文章版权归 Dreama 所有, 转载授权请联系: cnxy@88.com

如果本文对您有帮助,欢迎支持原创

支付宝

支付宝扫码支持

微信

微信赞赏支持