C#中的多播委托是什么?
拥有对多个方法的引用的委托称为多播委托。
让我们看一个例子-
示例
using System;delegate void myDelegate(int val1, int val2);
public class Demo {
public static void CalAdd(int val1, int val2) {
Console.WriteLine("{0} + {1} = {2}", val1, val2, val1 + val2);
}
public static void CalSub(int val1, int val2) {
Console.WriteLine("{0} - {1} = {2}", val1, val2, val1 - val2);
}
}
public class Program {
static void Main() {
myDelegate d = new myDelegate(Demo.CalAdd);
d += new myDelegate(Demo.CalSub);
d(45, 70);
d -= new myDelegate(Demo.CalAdd);
d(95, 70);
d += new myDelegate(Demo.CalSub);
d(88, 6);
d -= new myDelegate(Demo.CalAdd);
d(40, 20);
Console.Read();
}
}
在上面的示例中,我们的代表是-
delegate void myDelegate(int val1, int val2);
使用以下内容,我们在委托中为多个方法设置了引用,即CalAdd()
和CalSub()
-
myDelegate d = new myDelegate(Demo.CalAdd);d += new myDelegate(Demo.CalSub);
d(45, 70);
d -= new myDelegate(Demo.CalAdd);
d(95, 70);
d += new myDelegate(Demo.CalSub);
d(88, 6);
d -= new myDelegate(Demo.CalAdd);
d(40, 20);
以上是 C#中的多播委托是什么? 的全部内容, 来源链接: utcz.com/z/348863.html