委托与事件的理解说明

示例:使用委托
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");

   }

}

原文地址:https://www.cnblogs.com/top5/p/1584358.html