C# 多播委托示例
下面是组播委托的一个简单示例。
using System; delegate void MyDelegateMethod(); class MyDelegateSample { static void Main() { new MyDelegateSample(); } MyDelegateSample() { MyDelegateMethod myMethod = null; myMethod += new MyDelegateMethod(MyMethod1); myMethod += new MyDelegateMethod(MyMethod2); myMethod(); } void MyMethod1() { Console.WriteLine("In MyMethod1..."); } void MyMethod2() { Console.WriteLine("In MyMethod2..."); } }
委托(Delegate)是作为C#中的新类型对象的最好补充。它们也表示为指向函数的指针。
从技术上讲,delegate是一种引用类型,用于封装具有特定签名和返回类型的方法。
因为在本文中,我们在事件中心系统中讨论委托。
委托仅标识事件的一个订阅者(subscriber)。
因此,System.MulticastDelegate为委托添加了通知多个订阅者(subscriber)户的支持。
这是通过System.MulticastDelegate控制另一个System.MulticastDelegate实例实现的。
当我们向多播委托添加订阅者(subscriber)时,多播委托类创建委托类型的新实例,将所添加方法的对象引用和方法指针存储到新实例中,并将新委托实例作为委托实例列表中的下一项添加。实际上,多播委托类维护委托对象的链接列表。
多播委托可以持有和调用多个方法。在本例中,我们声明了一个名为MyDelegateMethod的简单委托,它可以保存并依次调用MyMethod1和MyMethod2方法。
日期:2020-04-11 23:03:42 来源:oir作者:oir