面试的时候估计都会被问过, 什么是委托, 事件是不是一种委托? 委托的优点都是什么? 我在项目中经常使用, 但是平时不注意整理概念性知识, 回答起来像是囫囵吞枣, 答不出个所以然来. 今天周末抽出来一些时间, 静下心来整理下. 下面我将采用一问一答的性质来整理和记录.
1. 什么是委托?
委托是一种类型安全的对象, 它是指向程序中的以后会被调用的函数方法 (可以是多个).
2. 事件是不是一种委托?
是, 是一种特殊的委托.
3. 委托怎么创建?
- // 委托类型包含三个主要信息:
- // 1. 它所调用的方法名称.
- // 2. 调用方法的参数 (可选).
- // 3. 该方法的返回类型 (可选).
- public delegate string Texts(int x, int y);
4. 委托的性质分为几种?
委托性质分为两种, 分别是异步委托, 同步委托.
5. 创建委托后, 程序运行的时候发生了什么?
编译器处理委托对象时候, 会自动产生一个派生自 System.MulticastDelegate 的密封类, 它和它的基类 System.Delegate. 一起为委托提供必要的基础设施.
通过 ildasm.exe 我们查看刚才创建的 Texts 委托, 发现它定义了 3 个公共方法.
- public string Invoke(int x, int y);
- public IAsyncResult BeginInvoke(int x, int y, AsynCallback cb, object state);
- public int EndInvoke(IAsyncResult result);
可以看出 BeginInvoke 用于异步调用.
6. 能不能写一个实战的例子?
- class Program
- {
- // 声明一个委托, 这个委托可以指向任何传入两个 int 类型参数, 并返回 int 类型的方法
- public delegate int Texts(int x, int y);
- public class SimpleMath
- {
- public static int Add(int x, int y)
- {
- return x + y;
- }
- public static int Subtract(int x, int y)
- {
- return x - y;
- }
- }
- static void Main(string[] args)
- {
- // 创建一个指向 SimpleMath 类中 Add 方法的对象
- Texts t = new Texts(SimpleMath.Add);
- // 使用委托对象间接调用 Add 方法
- Console.WriteLine("2+3={0}", t(2, 3));
- Console.ReadLine();
- }
- }
- View Code
7. 什么是委托的多播.
委托的多播可以理解为, 创建一个委托对象可以维护一个可调用方法的列表而不只是一个单独方法. 直接上代码可能更加直观.
- class Program
- {
- // 声明一个委托, 这个委托可以指向任何传入两个 int 类型参数, 并返回 int 类型的方法
- public static int a = 0;
- public delegate int Texts(int x, int y);
- public class SimpleMath
- {
- public static int Add(int x, int y)
- {
- return a = x + y;
- }
- public static int Subtract(int x, int y)
- {
- return a = x + y + a;
- }
- }
- static void Main(string[] args)
- {
- // 创建一个指向 SimpleMath 类中 Add 方法的对象
- Texts t = new Texts(SimpleMath.Add);
- // 委托的多播, 可以直接使用 +=
- t += SimpleMath.Subtract;
- t(2, 3);
- // 使用委托对象间接调用 Add 和 Subtract 方法
- Console.WriteLine("a=" + a + "");
- Console.ReadLine();
- }
- }
- View Code
8. 有没有快速创建委托的办法?
我们可以使用 Action<> 和 Func<> 快速创建委托.
- public static void TextAction(int x, int y)
- {
- Console.WriteLine("x=" + x + ",y=" + y + "");
- }
- static void Main(string[] args)
- {
- // 使用 Action<> 泛型委托快捷创建一个指向 TextAction 方法的委托. (注意 Action 只能指向没有返回值的方法)
- Action<int, int> action = new Action<int, int>(TextAction);
- action(1, 2);
- }
- View Code
- public static int Textfun(int x, int y)
- {
- return x + y;
- }
- static void Main(string[] args)
- {
- // 使用 fun<> 泛型委托快捷创建一个指向 Textfun 方法的委托. (注意 Func 最后一个参数值得是方法的返回值类型)
- Func<int, int, int> fun = new Func<int, int, int>(Textfun);
- Console.Write(fun.Invoke(2, 3));
- }
- View Code
暂时先整理这么多, 有哪块错误或遗漏, 欢迎大家指出和补充.
来源: https://www.cnblogs.com/xiaobaicode/p/11939122.html