c# 多播委托实现代码
下面是一个简单的 C# 多播委托实现示例:
using System;
delegate void MyDelegate(string message);
class Program
{
static void Main(string[] args)
{
MyDelegate del = MethodA;
del += MethodB;
del += MethodC;
del("Hello, World!");
}
static void MethodA(string message)
{
Console.WriteLine("MethodA: " + message);
}
static void MethodB(string message)
{
Console.WriteLine("MethodB: " + message);
}
static void MethodC(string message)
{
Console.WriteLine("MethodC: " + message);
}
}
在这个例子中,我们定义了一个名为 MyDelegate 的委托,它接受一个字符串参数并返回 void。然后,我们定义了三个方法 MethodA、MethodB 和 MethodC,它们都符合 MyDelegate 的签名。
在 Main 方法中,我们创建了一个 MyDelegate 实例 del,然后将 MethodA、MethodB 和 MethodC 添加到它的委托链中。最后,我们调用 del("Hello, World!"),这将依次调用 MethodA、MethodB 和 MethodC,并向它们传递相同的消息。
当我们运行这个程序时,输出将是:
MethodA: Hello, World!
MethodB: Hello, World!
MethodC: Hello, World!
这就是 C# 中多播委托的基本用法
原文地址: https://www.cveoy.top/t/topic/f2N2 著作权归作者所有。请勿转载和采集!