zoukankan      html  css  js  c++  java
  • 一个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
    !
  • 相关阅读:
    实战 Windows下搭建Objectivec的编译环境
    C# 协变和逆变 精解(直观明了,简单易懂)
    求两个字符串的最大公共串
    [C++][数据结构]队列(queue)的实现
    转换一个矩阵(2维数组)为HTML Table
    [C++][数据结构][算法]单链式结构的深拷贝
    LaTeX 中的特殊符号
    [C++11][数据结构]自己的双链表实现
    现代诗十则
    [C++11][算法][穷举]输出背包问题的所有可满足解
  • 原文地址:https://www.cnblogs.com/smwikipedia/p/1398105.html
Copyright © 2011-2022 走看看