当谈到C#中的委托时,多播委托是一个很有用的概念。委托本质上是一个指向一个或多个方法的引用。多播委托允许将多个方法绑定到一个委托实例上,并在调用委托时依次执行这些方法。
C#多播委托概念
多播委托是一个能够持有多个方法引用的委托类型。它可以将多个方法绑定到一个委托实例上,当调用该委托时,它按照绑定顺序依次执行这些方法。
C#多播委托使用场景
C#多播委托用法示例
假设有一个委托 Action,它代表一个不带参数、不返回任何值的方法。我们可以使用 += 和 -= 操作符来添加和移除方法。
- using System;
-
- class Program
- {
- public delegate void Action(); // 定义一个委托
-
- static void Main()
- {
- Action multicastDelegate = null;
-
- // 绑定多个方法到委托上
- multicastDelegate += Method1;
- multicastDelegate += Method2;
- multicastDelegate += Method3;
-
- // 调用委托,依次执行绑定的方法
- multicastDelegate?.Invoke();
- }
-
- static void Method1()
- {
- Console.WriteLine("Method 1 called");
- }
-
- static void Method2()
- {
- Console.WriteLine("Method 2 called");
- }
-
- static void Method3()
- {
- Console.WriteLine("Method 3 called");
- }
- }
-
在上面的示例中,当 multicastDelegate 被调用时,Method1、Method2 和 Method3 将会按顺序被执行。可以使用 -= 操作符来解除绑定的方法。
- multicastDelegate -= Method2; // 解除绑定 Method2
-
这样,当 multicastDelegate 被调用时,只会执行 Method1 和 Method3。