组合委托

来源:互联网 发布:unity 2d rpg 源码 编辑:程序博客网 时间:2024/06/05 23:53

组合委托。委托对象的一个有用属性是,它们可以“+”运算符来组合。组合的委托依次调用组成它的两个委托。只可组合相同类型的委托,并且委托类型必须具有 void 返回值。“-”运算符可用来从组合的委托移除组件委托。

using System;

delegate void MyDelegate(string s);

class MyClass

{

    public static void Hello(string s)

    {

        Console.WriteLine("  Hello, {0}!", s);

    }

    public static void Goodbye(string s)

    {

        Console.WriteLine("  Goodbye, {0}!", s);

    }

    public static void Main()

    {

        MyDelegate a, b, c, d;

        a = new MyDelegate(Hello);

        b = new MyDelegate(Goodbye);

        c = a + b;

        d = c - a;

        Console.WriteLine("Invoking delegate a:");

        a("A");

        Console.WriteLine("Invoking delegate b:");

        b("B");

        Console.WriteLine("Invoking delegate c:");

        c("C");

        Console.WriteLine("Invoking delegate d:");

        d("D");

    }

}

输出结果:

Invoking delegate a:

  Hello, A!

Invoking delegate b:

  Goodbye, B!

Invoking delegate c:

  Hello, C!

  Goodbye, C!

Invoking delegate d:

  Goodbye, D!

 

0 0
原创粉丝点击