且构网

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

WinForm控件查找奇思

更新时间:2022-08-22 10:20:42

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

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

 


  1. public delegate bool SearchHandler(Control ctrFind);  
  2.     public class WinSearch<T>  
  3.     {  
  4. //ctr:查找起点控件。  
  5.         public static T Search(Control ctr, SearchHandler handler)  
  6.         {  
  7.             if (handler == null)  
  8.                 throw new Exception("Handler must be not null");  
  9.             if (ctr == null)  
  10.                 throw new Exception("Parent Control must be not null");  
  11.             if (!(ctr is Control))  
  12.                 throw new Exception("The fist parameter must be innert from Control");  
  13.             return SearchProxy(ctr, handler);  
  14.         }  
  15.  
  16.         protected static T SearchProxy(Control ctr,SearchHandler handler)  
  17.         {  
  18.             if (ctr.Controls.Count < 1)  
  19.             {  
  20.                 return default(T);  
  21.             }  
  22.             else 
  23.             {  
  24.                 foreach (Control child in ctr.Controls)  
  25.                 {  
  26.                     if (child is T  && handler(child))//注意返回范型类型应是如此才会返回。  
  27.                     {  
  28.                         return (T)(object)child;  
  29.                     }  
  30.                     else 
  31.                     {  
  32.                         foreach (Control ch in child.Controls)  
  33.                         {  
  34.                             object obj = SearchProxy(ch, handler);  
  35.                             if (obj !=null)  
  36.                             {  
  37.                                 return (T)obj;  
  38.                             }  
  39.                         }  
  40.                     }  
  41.                 }  
  42.                 return default(T);  
  43.             }  
  44.         }  
  45.          
  46.               
  47.     }  
  48.     
  49. 测试体:  
  50.    
  51.  private void button1_Click(object sender, EventArgs e)  
  52.         {  
  53.             Button btn = WinSearch<Button>.Search(this, new SearchHandler(mehtod));  
  54.             if (btn != null)  
  55.             {  
  56.                 MessageBox.Show(btn.Text);  
  57.             }  
  58.         }  
  59.         public bool mehtod(Control ctr)  
  60.         {  
  61.             if (ctr.Text =="button2")  
  62.                 return true;  
  63.             return false;  
  64.         }  
WinForm控件查找奇思




 本文转自 破狼 51CTO博客,原文链接:http://blog.51cto.com/whitewolfblog/833551,如需转载请自行联系原作者