【總結】委託和匿名委託的比較

 

感受匿名委託使用起來更簡潔一點,不用在定義一個專用的委託函數來傳遞方法,也更能夠更好的理解委託。html

 

 

1、匿名委託函數

 

 1    #region 匿名委託
 2 
 3     //定義委託
 4     delegate string lookMe(string s);  5 
 6     protected void LinkButton1_Click(object sender, EventArgs e)  7  {  8         //匿名委託
 9         lookMe lm = delegate(string name) { return "親愛的 " + name + ",請看着個人眼睛!"; }; 10 
11         //匿名委託調用
12         string name1 = "jarod"; 13         Label1.Text = lm(name1); 14  } 15 
16     #endregion

 

 

2、實名委託spa

 

 1  #region 委託的應用
 2 
 3     //委託的定義
 4     public delegate string  deleRate(string year);  5 
 6     //三個方法的定義,以供委託調用
 7     public string year_2009(string s)  8     { Response.Write("2009" + s); return "2009" + s; }  9 
10     //三個方法的定義,以供委託調用
11     public string year_2008(string s) 12     { Response.Write("2008" + s); return "2008" + s; } 13 
14     //三個方法的定義,以供委託調用
15     public string year_2007(string s) 16     { Response.Write("2007" + s); return "2007" + s; } 17 
18     protected void Button1_Click(object sender, EventArgs e) 19  { 20         deleRate dr = new deleRate(year_2009); 21         dr += year_2008; 22         dr += year_2007; 23 
24         //直接用委託實例調用方法
25         Label1.Text = dr(""); 26 
27         //使用委託實現方法調用方法
28         Label1.Text = getYear(dr, ""); 29 
30         //使用委託實現方法調用方法,方法名做爲參數
31         Label1.Text = getYear(year_2008, ""); 32  } 33 
34     //執行委託的過程,把參數 year2 傳入實際執行的方法中去
35     public static string getYear(deleRate dr, string year2) 36     { return dr(year2); } 37 
38     #endregion

 

 

 

 


 

轉:https://www.cnblogs.com/jarod99/archive/2009/01/15/1376086.htmlcode

相關文章
相關標籤/搜索