zoukankan      html  css  js  c++  java
  • 委托与事件的理解说明

    示例:使用委托
    using System;
    class MyTime
    {

    public static void HelloTime(string s){ Console.WriteLine("hello{0}!The time is {1} now,s,DateTime.Now");}public static void Goodbye(string s){ Console.WriteLine("Goodbye{0}!The time is {1} now,s,DateTime.Now");}
    public static void SayTime(string s){ Console.WriteLine("{0}!The time is {1} now,s,DateTime.Now");}
    }

    Class TestDelegate
    {

    public static void main(){

    TimeDelegate a =new timeDelegate(MyTime.HelloTime);
    a("A");//相当于调用方法MyTime.HelloTime("A");

    TimeDelegate B =new timeDelegate(MyTime.HelloTime);
    B("B");//相当于调用方法MyTime.HelloTime("A");

    TimeDelegate C=a+B;//C相当于封装了两个方法HelloTime和GoodbyeTime;
    C("C");

    C-=a;//相当于把HelloTime方法移除.   委托使用"+", "+=" , "-" 和 "-="运算符向调用列表中增加或移除方法.
    C("C");

    }

    }

    事件:对象之间的交互是通过消息传递来实现的,而事件就是对象发送的信息.用来发现信号通知操作发生.引发(触发)事件的对象叫做事件发送方,捕获事件并对其作出响应的对象叫做事件接收方.在事件通信中,事件发送方不知道哪个对象或方法将接收到(处理)它引发事件.因此需要在发送方和接收方之间用一个纽带来联系,在C#中使用委托作为这个纽带.

    using System;
    public delegate void TimeEventHandler(string s);

    class MyTime()
    {

    public event TimeEventHandler Timer;//声明事件
    public void OnTimer(string s){if(null!=Timer) Timer(s);} //引发事件;

    }
    class ProcessTime
    {

    public void GenerateTime(string s)
                  console.writeline("hello {0}! The time is {1} now",s,Datetime.Now);

    }

    class TestTime
    {

       public static void main()
       {

        processTime p=new processTime();
        Mytime t=new MyTime();
        t.Timer+=new TimeEventHandler(p.GenerateTime);使事件与事件处理联系起来.
        t.OnTimer("Peter");

       }

    }

  • 相关阅读:
    用Oracle实现ASH的数据透视图
    Oracle AWR 之 通过dbms_workload_repository.awr_report_text(html)函数在客户端生成AWR报告
    (转)CentOS 7 安装 Python3、pip3
    (转) Linux 内核运行参数修改——sysctl命令
    (转)oracle linux 7 安装oracle 12c
    (转)Oracle与DB2在数据库高可用技术上的相同与差异探讨
    (转)OpenStack —— 原理架构介绍(一、二)
    (转)ELK原理与介绍
    (转)Db2 备份恢复性能问题诊断与调优
    (转)IBM AIX系统安装
  • 原文地址:https://www.cnblogs.com/top5/p/1584358.html
Copyright © 2011-2022 走看看