舉例來說,我們都知道int是儲存整數的資料型態,而String是用來儲存字串的資料型態。
而Delegate是用來儲存事件的資料型態,看完這句話後在來看以下的程式碼。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private int i; | |
//存放整數的資料型態 | |
private String strs; | |
//存放字串的資料型態 | |
private delegate void delegateTest(); | |
//存放無回傳值 無傳入值的方法 |
那我們該怎麼使用這個Delegate呢,先產生一個符合條件(無回傳值 無傳入值)的方法。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void A() { | |
System.Diagnostics.Debug.WriteLine("我是A"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//第一種 指定定義的方法 | |
delegateTest d1 = A; | |
//指定d1要執行的方法為A | |
d1(); | |
//印出 我是A | |
//第二種 直接實作方法 | |
delegateTest d2 = delegate () { | |
System.Diagnostics.Debug.WriteLine("我是d2"); | |
}; | |
d2(); | |
//印出 我是d2 | |
//第三種 Expression Lambda 語法 | |
delegateTest d3 = () => {System.Diagnostics.Debug.WriteLine("我是Lambda語法");}; | |
d3(); | |
//印出 我是Lambda語法 |
當你要使用的時候在決定要丟入什麼樣的型態,就像下面這個例子。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private delegate TResult Func<TArg0, TResult>(TArg0 t0); | |
//存放回傳值TResult 傳入值TArg0的方法 | |
private int M1(int a) { | |
return a; | |
} | |
private String M2(int b) { | |
return "M2"; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Func<int, int> f1 = M1; | |
//指定TArg0的型態為 int , TResult為 int | |
//此時你可以把它看成 private delegate int Func(int t0); | |
Func<int, String> f2 = M2; | |
//指定TArg0的型態為 int , TResult為 String | |
//此時你可以把它看成 private delegate String Func(int t0); | |
f2 = M1; | |
//錯誤 : 型態不符合 |
這樣一來你應該會對Delegate有一定的認識了。
沒有留言:
張貼留言