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
    !
  • 相关阅读:
    CCCC L2-023. 图着色问题【set去重判不同种类个数/简单图论/判断两相邻点是否存在同色以及颜色个数】
    百练 04 简单的整数划分问题
    NYOJ90 整数划分(经典递归和dp)
    图遍历问题
    图着色问题
    Java 大数(整数+浮点数) 基本函数
    根据规律绘制图形(俗称蛇皮走位)
    KMP算法之我见
    CCCC L1-039. 古风排版【图形输出/循环控制行列/模拟/细节】
    HYSBZ 2818 Gcd【欧拉函数/莫比乌斯】
  • 原文地址:https://www.cnblogs.com/smwikipedia/p/1398105.html
Copyright © 2011-2022 走看看