最近做WinForm程式,盡搞些動态生成控件的,每次尋找某個空間時總要一大堆代碼,簡單但是寫的多,煩啊。突然想起了Linq裡的表達式方式,但是項目用的類庫是2.0的。最後仿照Linq用範型寫了一個周遊類:減少了一大堆不必要的代碼。
代碼很簡單,就不用解釋了,直接貼↑。
<a></a>
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;
}
}
}
}
測試體:
private void button1_Click(object sender, EventArgs e)
Button btn = WinSearch<Button>.Search(this, new SearchHandler(mehtod));
if (btn != null)
MessageBox.Show(btn.Text);
public bool mehtod(Control ctr)
if (ctr.Text =="button2")
return true;
return false;
本文轉自破狼部落格園部落格,原文連結:http://www.cnblogs.com/whitewolf/archive/2009/11/20/1606587.html,如需轉載請自行聯系原作者