面試的時候估計都會被問過,什麼是委託,事件是否是一種委託?委託的優勢都是什麼?我在項目中常用,可是平時不注意整理概念性知識,回答起來像是囫圇吞棗,答不出個因此然來。今天週末抽出來一些時間,靜下心來整理下。下面我將採用一問一答的性質來整理和記錄。面試
1.什麼是委託?安全
委託是一種類型安全的對象,它是指向程序中的之後會被調用的函數方法(能夠是多個)。異步
2.事件是否是一種委託?ide
是,是一種特殊的委託。函數
3.委託怎麼建立?spa
1 // 委託類型包含三個主要信息: 2 // 1.它所調用的方法名稱。 3 // 2.調用方法的參數(可選)。 4 // 3.該方法的返回類型(可選)。 5 public delegate string Texts(int x, int y);
4.委託的性質分爲幾種?3d
委託性質分爲兩種,分別是異步委託,同步委託。code
5.建立委託後,程序運行的時候發生了什麼?對象
編譯器處理委託對象時候,會自動產生一個派生自System.MulticastDelegate的密封類,它和它的基類System.Delegate。一塊兒爲委託提供必要的基礎設施。blog
經過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 }
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 }
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 }
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 }
暫時先整理這麼多,有哪塊錯誤或遺漏,歡迎你們指出和補充。