一个C#中使用 event 和 delegate的小例子。

In event communication, the event sender class does not know which object or method will receive (handle) the events it raises. What is needed is an intermediary (or pointer-like mechanism) between the source and the receiver. The .NET Framework defines a special type (Delegate) that provides the functionality of a function pointer.

-------the relationship between Delegate & Event <MSDN>

 

Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Observer
{
    
public interface IMaster
    {
        
void buy_slave(ISlave some_slave);
        
void send_command();
    }

    
public interface ISlave
    {
        
void slave_do_work();
    }


    
class Program
    {
        
static void Main(string[] args)
        {
            master master1 
= new master();
            slave slave1 
= new slave();

            master1.buy_slave(slave1);
            master1.send_command();
        }

    }

    
public class master:IMaster
    {
        
public delegate void some_function();
        
public event some_function some_event;

        
#region IMaster Members

        
public void buy_slave(ISlave some_slave)
        {
            some_event 
+= some_slave.slave_do_work;
        }


        
public void send_command()
        {
            Console.WriteLine(
"master: Where is my slave?");
            some_event();
        }

        
#endregion
    }
    
public class slave:ISlave
    {

        
#region ISlave Members

        
public void slave_do_work()
        {
            Console.WriteLine(
"slave: I am here, my lord!");
        }

        
#endregion
    }
}

 

输出:

 

Code
master: Where is my slave?
slave: I am here, my lord
!

posted on 2009-02-25 17:42  smwikipedia  阅读(532)  评论(1编辑  收藏  举报

导航