一直以来对delegate都是一知半解,通过看网上的一些例子还是有些稀里糊涂,不知道是自己太笨还是文章没说清楚.十分morose.今天偶尔在网上看到一个关于理解delegate的例子,觉得很是通俗易懂,所以就转录过来和大家分享一下,通过初步理解,还是能够十分顺利的写出代码实例来:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DelegateTest1
{
public delegate void OnEventHandler();//定义一个delegate
public class Cat
{
public static event OnEventHandler cry;//定义cry事件
public Cat()//cat类构造函数,每当实例化一个cat对象时,cat就来了..
{
Console.WriteLine("Cat:I'm coming.");
}
public virtual void onCry()//实例化cat对象后可以随时调用onCry方法
{
Console.WriteLine("Cat:miao,miao...");
if (cry != null)//如果cry事件列表不为空
{
cry();//引发cry事件,mouse得到了通知,赶快逃之夭夭了...
}
}
}
public class Mouse
{
public Mouse()
{
Cat.cry+=new OnEventHandler(run);//和事件绑定,一旦发生cry事件,通过delegate将调用run方法
Console.WriteLine("Mouse:I am find some food,and I should listen to the cat's crying");
}
public void run()
{
Console.WriteLine("Mouse:cat is coming,I must go now!");
}
}
class Program
{
static void Main(string[] args)
{
Mouse mouse = new Mouse();
Cat cat = new Cat();
cat.onCry();
Console.ReadLine();
}
}
}