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");

       }

    }

  • 相关阅读:
    我的第一个可用的Windows驱动完成了
    据说是一种很古老的方法
    起一卦,测今天工作,问题不少
    起一卦,找房子,马上没房子住了
    哈哈哈哈,我竟然发现了个MSDN里面的笔误
    起一卦,看现在我的工程进度怎么样。
    起卦帮同学看工作,应了。
    2012年10月17日帮朋友算得第一卦
    2013年1月13日帮朋友测的第二卦,有些地方没看出来
    bzoj2588 Spoj 10628. Count on a tree
  • 原文地址:https://www.cnblogs.com/top5/p/1584358.html
Copyright © 2011-2022 走看看