[转载]委托代理Delegate(组合委托)

.Net学习笔记——委托代理Delegate2(组合委托)- -
                                       
组合委托
委托对象的一个有用属性是,它们可以“
+”运算符来组合。组合的委托可调用组成它的那两个委托。只有相同类型的委托才可以组合。 

-”运算符可用来从组合的委托移除组件委托。

// compose.cs
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;

        
// Create the delegate object a that references 
        
// the method Hello:
        a = new MyDelegate(Hello);
        
// Create the delegate object b that references 
        
// the method Goodbye:
        b = new MyDelegate(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;

        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
!
posted @ 2007-09-24 13:26  水静痕迹  阅读(140)  评论(0编辑  收藏  举报