委托 delegate關鍵字,可以實現將函數作為參數傳遞
1、基本用法
委托是一個數據類型,與類同等級,用於指向某一個方法,然后通過委托來調用該方法
static delegate int delegateAdd(int a,int b);//創建一個返回值int,兩個參數都是int的委托 class wt{ //先創建兩個示例函數,返回值和參數類型與委托相同,才能傳遞給委托.為方便演示,暫時方法設置成static public static int add1(int a,int b){ return a+b; } public static int add2(int a,int b){ return a+b+10; } static void Main(string[] args){ delegateAdd a = new delegateAdd(add1);//實例化一個委托,將add方法賦給委托,也可以delegateAdd a =add1;簡寫 delegateAdd(1,2);//等同於調用add1,返回3 delegateAdd+=add2;//可以用+=和-=操作委托當中包含的方法,委托可以看做一個方法的集合 delegateAdd(1,2);//調用add1和add2,委托的返回值為最后一個方法的返回值,此處為13 } }
2、Action和Func
系統本身有兩個定義好的委托類型,其中Action是無返回值(void)類型方法,Func有返回值
class wt{ public static void say(string s){//參數string,無返回值 Console.WriteLine(s); } public static string add(int a,int b){//參數兩個int,返回值string int c=a+b; Console,WriteLine(c); return c.toString(); } static static void main(string[] args){ Action<string> say1 = say;//Action示例,尖括號內是參數類型列表,實例化一個無返回值委托實例 say1("Hello World");//輸出Hello World Func<int,int,string> add1 = add;//Func示例,尖括號里前面是參數列表,最后一個是返回值類型,實例化一個有返回值委托實例 add1(1,2);//輸出3,返回字符串類型"3" } }
3、通過利用實例,將方法名作為參數的實現
class wt{ public void say(string s){ Console.WriteLine("我想說:"+s); } public void eat(string s){ Console.WriteLine("我吃了:"+s); } public void dosth(Action<string> act,string c){ act(c); } static void Main(string[] args){ wt wt1 = new wt(); wt.dosth(wt.say,"你好"); wt.dosth(wt.eat,"蘋果"); } }
4、使用匿名函數作為方法的參數
基本格式 方法名( delegate (參數列表){方法體} );
class wt{ public void dosth(Action<string> act,string c){ act(c); } public string dosth_2(Func<int,int,string> act,int a,int b){ act(c); } static void Main(string[] args){ wt wt1 = new wt(); //以下為使用delegate構造匿名函數方法 wt.dosth(delegate (string s){Console.WriteLine("我想說:"+s);},"你好"); wt.dosth(delegate (string s){Console.WriteLine("我吃了:"+s);},"蘋果"); wt.dosth_2(delegate (int a,int b){ int c = a+b; return c.toString(); },1,2); } }
5、匿名函數的更簡單寫法,lambda表達式
基本格式 方法名( (參數列表) => {方法體} );
class wt{ public void dosth(Action<string> act,string c){ act(c); } public string dosth_2(Func<int,int,string> act,int a,int b){ act(c); } static void Main(string[] args){ wt wt1 = new wt(); //以下為使用lambda表達式構造匿名函數方法 wt.dosth((string s)=>{Console.WriteLine("我想說:"+s);},"你好"); wt.dosth((string s)=>{Console.WriteLine("我吃了:"+s);},"蘋果"); wt.dosth_2((int a,int b)=>{ int c = a+b; return c.toString(); },1,2); } }
6、使用委托構造事件
可以類比一些圖形界面編程中的監聽,當執行某操作時觸發,並執行某一操作
下面以Dog對象為例,有run方法,有v速度屬性,事件設置為當狗在跑的時候觸發,進行廣播速度值
public class Dog{ public int v; public event Action onRun;//event關鍵字定義事件,無參數直接用Action不加尖括號 public Dog(){//初始化v v=10; } public void run(){ Console.WriteLine("狗在跑"); onRun(); } } class wt{ static void Main(string[] args){ Dog dg=new Dog(); dg.onRun += (()=>{Console.WriteLine("速度是:"+dg.v);}); dg.run(); //輸出結果: //狗在跑 //速度是:10 } } //如果需要對事件進行刪除,那么可以不使用匿名函數