1.委託的定義
委託可以看成是一種資料類型,可以用於定義變數能接受的值只能是一個方法。
委託簡單的樣本:
複製代碼 代碼如下:namespace DelegateDemo
{
class Program
{
public delegate int MathOptDelegate(int value1,int value2);
public int add(int value1, int value2)
{
return value1 + value2;
}
static void Main(string[] args)
{
MathOptDelegate mod;
Program p = new Program();
mod =p.add;
Console.WriteLine(mod(3,5));
Console.ReadKey();
}
}
}
利用委託的建構函式建立委託
複製代碼 代碼如下:namespace DelegateDemo
{
class Program
{
public delegate int MathOptDelegate(int value1,int value2);
public int add(int value1, int value2)
{
return value1 + value2;
}
static void Main(string[] args)
{
Program p = new Program();
MathOptDelegate mod = new MathOptDelegate(p.add);
Console.WriteLine(mod(3,5));
Console.ReadKey();
}
}
}
從這個樣本中可以得出這樣的直觀印象:
委託可以堪稱是一個方法的容器,將某一個具體的方法裝入後,就可以把它當成方法一樣使用。
2.委託的調用列表
從上一個例子看,委託變數可以引用某一個方法,調用它就相當於調用這個方法。
如果委託今年僅是方法調用的另一種形式,那何必多此一舉引入委託這一特性?直接調用方法不是更簡單明了?
因為委託變數不僅可以引用另一個方法,還可以組合多的方法並批量執行它們。
複製代碼 代碼如下:namespace DelegateDemo2
{
class Program
{
public delegate void MyDelegate(String str);
public static void hello(String str)
{
Console.WriteLine(str+"你好");
}
public static void goodbye(String str)
{
Console.WriteLine(str+"再見");
}
static void Main(string[] args)
{
MyDelegate a,b,c,d;
a = Program.hello;
a("a");
b = Program.goodbye;
b("b");
c = a + b;//等價將兩個方法體合并
c("c");// c你好 c再見
d = c - a;
d("d");//d再見
Console.ReadKey();
}
}
}
像C這樣的委託變數可稱為多路委託變數。
可以用加法運算子來組合單個委託變數為多路委託變數。類似的,也可以使用減法運算子來從一個多路委託變數中移除某個委託變數。
複製代碼 代碼如下:namespace DelegateDemo2
{
class Program
{
public delegate void MyDelegate(String str);
public static void hello(String str)
{
Console.WriteLine(str+"你好");
}
public static void goodbye(String str)
{
Console.WriteLine(str+"再見");
}
static void Main(string[] args)
{
MyDelegate a,b,c,d;
a = Program.hello;
a("a");
b = Program.goodbye;
b("b");
c = a + b;//等價將兩個方法體合并
c("c");// c你好 c再見
d = c - a;
d("d");//d再見
Delegate[] ds;
ds = c.GetInvocationList();
foreach(Delegate s in ds)
{
Console.WriteLine(s);
//DelegateDemo2.Program+MyDelegate
//DelegateDemo2.Program+MyDelegate
}
Console.WriteLine(ds.Length);
Console.ReadKey();
}
}
}
如果委託定義的方法有傳回值,則多路委託變數的傳回值為委託調用列表中最後一個方法的傳回值,中間調用的方法傳回值會被丟棄。
使用泛型委派:
Func系列委託
以下是Func熄了委託的定義,依其泛型型別參數的多少有多個重載形式:
public delegate TResult Func<Tresult>();
public delegate TResult Func<T,Tresult>();