代码改变世界

WinForm控件查找奇思

  破狼  阅读(2453)  评论(15编辑  收藏  举报
     最近做WinForm程序,尽搞些动态生成控件的,每次寻找某个空间时总要一大堆代码,简单但是写的多,烦啊。突然想起了Linq里的表达式方式,但是项目用的类库是2.0的。最后仿照Linq用范型写了一个遍历类:减少了一大堆不必要的代码。

代码很简单,就不用解释了,直接贴↑。

 

复制代码

public delegate bool SearchHandler(Control ctrFind);
    
public class WinSearch<T>
    
{
//ctr:查找起点控件。

        public static T Search(Control ctr, SearchHandler handler)
        
{
            
if (handler == null)
                
throw new Exception("Handler must be not null");
            
if (ctr == null)
                
throw new Exception("Parent Control must be not null");
            
if (!(ctr is Control))
                
throw new Exception("The fist parameter must be innert from Control");
            
return SearchProxy(ctr, handler);
        }


        
protected static T SearchProxy(Control ctr,SearchHandler handler)
        
{
            
if (ctr.Controls.Count < 1)
            
{
                
return default(T);
            }

            
else
            
{
                
foreach (Control child in ctr.Controls)
                
{
                    
if (child is T  && handler(child))//注意返回范型类型应是如此才会返回。
                    
{
                        
return (T)(object)child;
                    }

                    
else
                    
{
                        
foreach (Control ch in child.Controls)
                        
{
                            
object obj = SearchProxy(ch, handler);
                            
if (obj !=null)
                            
{
                                
return (T)obj;
                            }

                        }

                    }

                }

                
return default(T);
            }

        }

       

            
    }

复制代码

 

测试体:

 

复制代码
 private void button1_Click(object sender, EventArgs e)
        
{
            Button btn 
= WinSearch<Button>.Search(thisnew SearchHandler(mehtod));
            
if (btn != null)
            
{
                MessageBox.Show(btn.Text);
            }

        }

        
public bool mehtod(Control ctr)
        
{
            
if (ctr.Text =="button2")
                
return true;
            
return false;
        }
复制代码

 

 

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示