面試的時候估計都會被問過,什么是委托,事件是不是一種委托?委托的優點都是什么?我在專案中經常使用,但是平時不注意整理概念性知識,回答起來像是囫圇吞棗,答不出個所以然來,今天周末抽出來一些時間,靜下心來整理下,下面我將采用一問一答的性質來整理和記錄,
1.什么是委托?
委托是一種型別安全的物件,它是指向程式中的以后會被呼叫的函式方法(可以是多個),
2.事件是不是一種委托?
是,是一種特殊的委托,
3.委托怎么創建?
1 // 委托型別包含三個主要資訊: 2 // 1.它所呼叫的方法名稱, 3 // 2.呼叫方法的引數(可選), 4 // 3.該方法的回傳型別(可選), 5 public delegate string Texts(int x, int y);
4.委托的性質分為幾種?
委托性質分為兩種,分別是異步委托,同步委托,
5.創建委托后,程式運行的時候發生了什么?
編譯器處理委托物件時候,會自動產生一個派生自System.MulticastDelegate的密封類,它和它的基類System.Delegate,一起為委托提供必要的基礎設施,
通過ildasm.exe我們查看剛才創建的Texts委托,發現它定義了3個公共方法,
1 public string Invoke(int x, int y); 2 public IAsyncResult BeginInvoke(int x, int y, AsynCallback cb, object state); 3 public int EndInvoke(IAsyncResult result);
可以看出BeginInvoke用于異步呼叫,
6.能不能寫一個實戰的例子?
1 class Program 2 { 3 //宣告一個委托,這個委托可以指向任何傳入兩個int型別引數,并回傳int型別的方法 4 public delegate int Texts(int x, int y); 5 public class SimpleMath 6 { 7 public static int Add(int x, int y) 8 { 9 return x + y; 10 } 11 public static int Subtract(int x, int y) 12 { 13 return x - y; 14 } 15 16 } 17 static void Main(string[] args) 18 { 19 //創建一個指向SimpleMath類中Add方法的物件 20 Texts t = new Texts(SimpleMath.Add); 21 22 //使用委托物件間接呼叫Add方法 23 Console.WriteLine("2+3={0}", t(2, 3)); 24 Console.ReadLine(); 25 26 } 27 }View Code
7.什么是委托的多播,
委托的多播可以理解為,創建一個委托物件可以維護一個可呼叫方法的串列而不只是一個單獨方法, 直接上代碼可能更加直觀,
1 class Program 2 { 3 //宣告一個委托,這個委托可以指向任何傳入兩個int型別引數,并回傳int型別的方法 4 public static int a = 0; 5 public delegate int Texts(int x, int y); 6 public class SimpleMath 7 { 8 public static int Add(int x, int y) 9 { 10 return a = x + y; 11 } 12 public static int Subtract(int x, int y) 13 { 14 return a = x + y + a; 15 } 16 17 } 18 static void Main(string[] args) 19 { 20 //創建一個指向SimpleMath類中Add方法的物件 21 Texts t = new Texts(SimpleMath.Add); 22 //委托的多播,可以直接使用+= 23 t += SimpleMath.Subtract; 24 t(2, 3); 25 //使用委托物件間接呼叫Add和Subtract方法 26 Console.WriteLine("a=" + a + ""); 27 Console.ReadLine(); 28 29 } 30 }View Code
8.有沒有快速創建委托的辦法?
我們可以使用Action<>和Func<>快速創建委托,
1 public static void TextAction(int x, int y) 2 { 3 Console.WriteLine("x=" + x + ",y=" + y + ""); 4 } 5 static void Main(string[] args) 6 { 7 8 //使用Action<>泛型委托快捷創建一個指向 TextAction 方法的委托, (注意Action 只能指向沒有回傳值的方法) 9 Action<int, int> action = new Action<int, int>(TextAction); 10 action(1, 2); 11 12 }View Code
1 public static int Textfun(int x, int y) 2 { 3 return x + y; 4 } 5 static void Main(string[] args) 6 { 7 8 //使用fun<>泛型委托快捷創建一個指向 Textfun 方法的委托, (注意Func 最后一個引數值得是方法的回傳值型別) 9 Func<int, int, int> fun = new Func<int, int, int>(Textfun); 10 Console.Write(fun.Invoke(2, 3)); 11 12 }View Code
暫時先整理這么多,有哪塊錯誤或遺漏,歡迎大家指出和補充,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/100043.html
標籤:C#
