现在的位置: 首页 > 综合 > 正文

多播委托(multicast delegate)

2012年07月26日 ⁄ 综合 ⁄ 共 1817字 ⁄ 字号 评论关闭

还是老规矩,先看代码:)

using System;

class MulticastTester
{
    
delegate void Greeting();
    
    
public static void SayThankYou()
    
{
        Console.WriteLine(
"Thank you!");
    }


    
public static void SayGoodMorning()
    
{
        Console.WriteLine(
"Good morning!");
    }


    
public static void SayGoodnight()
    
{
        Console.WriteLine(
"Goodnight");
    }

    
    
public static void Main()
    
{
        Greeting myGreeting 
= new Greeting(SayThankYou);
        Console.WriteLine(
"My single greeting:");
        myGreeting();
        
        Greeting yourGreeting 
= new Greeting(SayGoodMorning);        
        Console.WriteLine(
"\nYour single greeting:");
        yourGreeting();
        
        Greeting ourGreeting 
= myGreeting + yourGreeting;
        Console.WriteLine(
"\nOur multicast greeting:");
        ourGreeting();

        ourGreeting 
+= new Greeting(SayGoodnight);
        Console.WriteLine(
"\nMulticast greeting which includes Goodnight:");
        ourGreeting();
        
        ourGreeting 
= ourGreeting - yourGreeting;
        Console.WriteLine(
"\nMulticast greeting without your greeting:");
        ourGreeting();
        
        ourGreeting 
-= myGreeting;
        Console.WriteLine(
"\nSingle greeting without your greeting and my greeting:");
        ourGreeting();
    }

}

在MulticastTester类的第一个语句就是我们的委托,跟上次的委托是一样的定义方法,只是这次的委托Greeting没有返回值[1]也没有参数,其实想想也知道Greeting就只是一个动作而已:)

然后有三个静态方法,说谢谢,说早安,说晚安。等待我们用委托来封装。

在Main()方法中,我们首先用一个委托myGreeting封装了SayThankYou,然后用另一个委托yourGreeting封装了SayGoodMorning,这跟我们前面讲的委托是一样的。

第三个ourGreeting并没有明显地封装一个方法,而是把前面两个委托加了起来。这就是我们这次的主题——多播委托。这样一加,ourGreeting就封装了所加委托封装的所有方法。

第四个委托还是我们的ourGreeting,但是它又封装了一个新的方法SayGoodNight,并使用了操作符+=,这时候我们的ourGreeting封装了三个方法。

那我突然后悔了,要除去一个方法怎么办?那么就请看我们第五个和第六个委托(其实都是ourGreeting,呵呵),使用两种办法除去方法。

经过我的测试,ourGreeting = ourGreeting - new Greeting(SayThankYou)这样也是可以多播委托中的方法的。

[1]多播委托必须返回void

抱歉!评论已关闭.