C#委托&多播委托
·
在 C# 中,委托(Delegate) 是一种类型安全的函数指针,用于封装方法的引用。它允许将方法作为参数传递、存储或异步调用。
以下是一个完整的经典示例,演示了如何声明、实例化和使用委托:
using System;
// 1. 声明一个委托类型,表示接受两个整数并返回整数的方法
public delegate int MathOperation(int a, int b);
class Program
{
// 2. 定义几个与委托签名匹配的方法
static int Add(int x, int y)
{
return x + y;
}
static int Subtract(int x, int y)
{
return x - y;
}
static int Multiply(int x, int y)
{
return x * y;
}
// 3. 定义一个使用委托的方法
static void PerformOperation(MathOperation operation, int a, int b)
{
int result = operation(a, b);
Console.WriteLine("结果: " + result);
}
static void Main(string[] args)
{
// 4. 实例化委托
MathOperation opAdd = new MathOperation(Add);
MathOperation opSubtract = new MathOperation(Subtract);
MathOperation opMultiply = new MathOperation(Multiply);
// 5. 使用委托调用不同的方法
Console.WriteLine("执行加法:");
PerformOperation(opAdd, 10, 5);
Console.WriteLine("执行减法:");
PerformOperation(opSubtract, 10, 5);
Console.WriteLine("执行乘法:");
PerformOperation(opMultiply, 10, 5);
}
}
输出结果:
执行加法:
结果为:15
执行减法:
结果为:5
执行乘法:
结果为:50
多播委托(合并委托)
委托对象有一个非常有用的属性,那就是可以通过使用+运算符将多个对象分配给一个委托实例,同时还可以使用-运算符从委托中移除已分配的对象,当委托被调用时会依次调用列表中的委托。委托的这个属性被称为委托的多播,也可称为组播,利用委托的这个属性,您可以创建一个调用委托时要调用的方法列表。
using System;
// 定义一个委托类型
public delegate void MyDelegate(string message);
class Program
{
// 方法1
public static void Method1(string message)
{
Console.WriteLine("Method1: " + message);
}
// 方法2
public static void Method2(string message)
{
Console.WriteLine("Method2: " + message.ToUpper());
}
// 方法3
public static void Method3(string message)
{
Console.WriteLine("Method3: " + message.ToLower());
}
static void Main(string[] args)
{
// 创建两个委托实例
MyDelegate del1 = new MyDelegate(Method1);
MyDelegate del2 = new MyDelegate(Method2);
MyDelegate del3 = new MyDelegate(Method3);
// 使用 "+" 运算符组合委托(创建多播委托)
MyDelegate multicastDel = del1 + del2 + del3;
// 调用多播委托
Console.WriteLine("Calling multicast delegate:");
multicastDel("Hello, Multicast!");
// 移除某个方法
multicastDel -= del2;
Console.WriteLine("\nAfter removing Method2:");
// 再次调用多播委托
multicastDel("Hello Again!");
}
}
输出结果:
Calling multicast delegate:
method1: Hello, Multicast!
method2: HELLO, MULTICAST!
Method3: hello, multicast!After removing Method2:
method1: Hello Again!
Method3: hello again!
说明:
-
MyDelegate是一个多播委托,它可以绑定多个方法。 -
使用
+操作符将多个方法合并到同一个委托中。 -
调用委托时,所有绑定的方法都会按添加顺序执行。
-
使用
-操作符可以从多播委托中移除特定方法。
更多推荐



所有评论(0)