C#——如何合并委托(多播委托)

我不是女神ヾ 2023-01-03 04:22 151阅读 0赞

C#——如何合并委托(多播委托)

此示例演示如何创建多播委托。 委托对象的一个有用属性在于可通过使用 + 运算符将多个对象分配到一个委托实例。 多播委托包含已分配委托列表。 此多播委托被调用时会依次调用列表中的委托。 仅可合并类型相同的委托。

-运算符可用于从多播委托中删除组件委托。

示例

  1. using System;
  2. // Define a custom delegate that has a string parameter and returns void.
  3. delegate void CustomDel(string s);
  4. class TestClass
  5. {
  6. // Define two methods that have the same signature as CustomDel.
  7. static void Hello(string s)
  8. {
  9. Console.WriteLine($" Hello, {s}!");
  10. }
  11. static void Goodbye(string s)
  12. {
  13. Console.WriteLine($" Goodbye, {s}!");
  14. }
  15. static void Main()
  16. {
  17. // Declare instances of the custom delegate.
  18. CustomDel hiDel, byeDel, multiDel, multiMinusHiDel;
  19. // In this example, you can omit the custom delegate if you
  20. // want to and use Action<string> instead.
  21. //Action<string> hiDel, byeDel, multiDel, multiMinusHiDel;
  22. // Create the delegate object hiDel that references the
  23. // method Hello.
  24. hiDel = Hello;
  25. // Create the delegate object byeDel that references the
  26. // method Goodbye.
  27. byeDel = Goodbye;
  28. // The two delegates, hiDel and byeDel, are combined to
  29. // form multiDel.
  30. multiDel = hiDel + byeDel;
  31. // Remove hiDel from the multicast delegate, leaving byeDel,
  32. // which calls only the method Goodbye.
  33. multiMinusHiDel = multiDel - hiDel;
  34. Console.WriteLine("Invoking delegate hiDel:");
  35. hiDel("A");
  36. Console.WriteLine("Invoking delegate byeDel:");
  37. byeDel("B");
  38. Console.WriteLine("Invoking delegate multiDel:");
  39. multiDel("C");
  40. Console.WriteLine("Invoking delegate multiMinusHiDel:");
  41. multiMinusHiDel("D");
  42. }
  43. }
  44. /* Output:
  45. Invoking delegate hiDel:
  46. Hello, A!
  47. Invoking delegate byeDel:
  48. Goodbye, B!
  49. Invoking delegate multiDel:
  50. Hello, C!
  51. Goodbye, C!
  52. Invoking delegate multiMinusHiDel:
  53. Goodbye, D!
  54. */

发表评论

表情:
评论列表 (有 0 条评论,151人围观)

还没有评论,来说两句吧...

相关阅读

    相关 C#委托

    一、什么是委托 委托是一种类型,就跟int,double,struct,string,class一样。它定义了一个函数的类型。现在,我们有一个方法,我们希望它的参数是某个

    相关 C#——委托

    C\——委托 委托是一种引用类型,表示对具有特定参数列表和返回类型的方法的引用。 在实例化委托时,你可以将其实例与任何具有兼容签名和返回类型的方法相关联。 你可以通过委托

    相关 C#委托

    委托: 委托定义了方法的类型,使得方法可以作为另一个方法的参数来进行传递,这样可以在程序中避免使用大量的判断语句,同时使程序具有更好的扩展性。 可以将多个方法绑定到同一个委

    相关 c#委托

    首先创建个控制台应用程序在Program下创建一个无参数无返回值的静态方法,可以输出一句话 static void Text() { Cons

    相关 C# 委托

    一、什么是委托?   初次理解这么抽象的概念确实有点挺难的,如果学过C语言,可能知道C语言里可以把一个方法当做参数来传递,委托大概类似也是这样一个原理。 想象一下,在一个

    相关 C# 委托

    委托 作用:将多个参数相同的方法,进行委托统一调用,将参数和调用方法传递给委托,由委托调用。 好处:可以将多个方法内相同的部分提取出来,根据参数和方法参数,调用需要的