[原创]老鼠->猫->人 事件触发
[原创]老鼠->猫->人 事件触发
扫一扫加作者微信
昨天晚上某个群里的朋友说他在面试.NET的时候碰到这个“老鼠,猫,人事件触发”题了,答得不是很清楚,正好自己也很久没写自定义事件的代码了,早上起来就顺便写了个,发上来让大家找找茬。
在定义事件前首先要定义一个委托类型,以用于该事件,而且返回类型和参数必须匹配。
namespace www.csframework.com
{
public delegate void MessageHandler(); //消息委托
class Program
{
static void Main(string[] args)
{
Mouse m = new Mouse();
Cat c = new Cat();
Man man = new Man();
m.MouseMoving+=new MessageHandler(c.CatMove); //=>指定事件触发
c.CatMoving += new MessageHandler(man.ManMove);//=>指定时间出发
Console.WriteLine("Begin:");
m.MouseMove();
}
}
class Mouse
{
public event MessageHandler MouseMoving;
public void MouseMove()
{
Console.WriteLine("A mouse is moving.");
MouseMoving();
}
}
class Cat
{
public MessageHandler CatMoving;
public void CatMove()
{
Console.WriteLine("A cat find the mouse,and catches it.");
CatMoving();
}
}
class Man
{
public void ManMove()
{
Console.WriteLine("A man finds his cat are eating a mouse.");
}
}
}
{
public delegate void MessageHandler(); //消息委托
class Program
{
static void Main(string[] args)
{
Mouse m = new Mouse();
Cat c = new Cat();
Man man = new Man();
m.MouseMoving+=new MessageHandler(c.CatMove); //=>指定事件触发
c.CatMoving += new MessageHandler(man.ManMove);//=>指定时间出发
Console.WriteLine("Begin:");
m.MouseMove();
}
}
class Mouse
{
public event MessageHandler MouseMoving;
public void MouseMove()
{
Console.WriteLine("A mouse is moving.");
MouseMoving();
}
}
class Cat
{
public MessageHandler CatMoving;
public void CatMove()
{
Console.WriteLine("A cat find the mouse,and catches it.");
CatMoving();
}
}
class Man
{
public void ManMove()
{
Console.WriteLine("A man finds his cat are eating a mouse.");
}
}
}
扫一扫加作者微信
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网