木子屋 Dnawo's BLOG

合并委托(多路广播委托)

👤 dnawo 📅 2007-12-29 👁 4969 👍 0 💬 0 🔄 来源:MSDN
委托对象的一个用途在于:可以使用 + 运算符将它们分配给一个要成为多路广播委托的委托实例,注意只有相同类型的委托才可以组合;可以使用- 运算符从组合的委托移除组件委托。

delegate void Del(string s);

class TestClass
{
    static void Hello(string s)
    {
        System.Console.WriteLine("  Hello, {0}!", s);
    }

    static void Goodbye(string s)
    {
        System.Console.WriteLine("  Goodbye, {0}!", s);
    }

    static void Main()
    {
        Del a, b, c, d;

        // Create the delegate object a that references 
        // the method Hello:
        a = Hello;

        // Create the delegate object b that references 
        // the method Goodbye:
        b = Goodbye;

        // The two delegates, a and b, are composed to form c: 
        c = a + b;

        // Remove a from the composed delegate, leaving d, 
        // which calls only the method Goodbye:
        d = c - a;

        System.Console.WriteLine("Invoking delegate a:");
        a("A");
        System.Console.WriteLine("Invoking delegate b:");
        b("B");
        System.Console.WriteLine("Invoking delegate c:");
        c("C");
        System.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)

暂无评论。

验证码
评论需审核通过后显示
← 上一篇 一个很COOL的图片验证码程序[含源码] 下一篇 → 何时使用委托而不使用接口