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
    !
  • 相关阅读:
    .NET之API版本控制
    接口管理平台YApi
    .NET之WebAPI
    Hyperv安装Centos7
    nginx添加https模块
    基于centos8镜像,打包php的docker镜像
    jmeter生成HTML性能测试报告(转载)
    jmeter相关(转载)
    接口测试总结(转载)
    【解决了一个小问题】alert manager中的cluster.advertiseaddress参数是什么意思?
  • 原文地址:https://www.cnblogs.com/smwikipedia/p/1398105.html
Copyright © 2011-2022 走看看