今天要學的是委託
委託的基本形式
直接上程式碼
public delegate int AddDelegate(int x,int y);
class Program
{
static void Main(string[] args)
{
int x=;int y=;
AddDelegate addDelegate = new AddDelegate(Add); int result = addDelegate(x, y);
Console.WriteLine("執行結果是:" + result);
Console.ReadLine();
} static int Add(int x, int y)
{
return x + y;
}
}
上面是最原始的委託。但是有人開始說了,我的委託可能只是用一次,還要這麼羅嗦的程式碼,累死人....;還有人會說,例項化委託會有資源消耗,我不想例項化。於是就有了委託的第二種樣式和第三種樣式
匿名委託
去掉了靜態函式
public delegate int AddDelegate(int x,int y);
class Program
{
static void Main(string[] args)
{
int x=;int y=; AddDelegate addDelegate1 = new AddDelegate( delegate(int a,int b){
return a + b;
});
int result = addDelegate1(x, y);
Console.WriteLine("執行結果是:" + result);
Console.ReadLine();
}
}
或者lamdba的寫法
public delegate int AddDelegate(int x,int y);
class Program
{
static void Main(string[] args)
{
int x=;int y=; AddDelegate addDelegate2 = (int a, int b) =>
{
return a + b;
};
int result = addDelegate2(x, y);
Console.WriteLine("執行結果是:" + result);
Console.ReadLine();
}
}
隨著.net版本的演變,出現了Func和Action,它們其實是.net內部封裝好的委託,方便大家使用,詳細咱這裡就不再介紹了。