C#委托和事件练习
2,猫守在老鼠洞口,等着老鼠出来,老鼠一出来,猫就扑了上去。编程模拟之。 展开
O(∩_∩)O~,代码和效果见下
1.
using System;
namespace baiduDemo
{
class Program1
{
static void Main(string[] args)
{
Firends f1 = new Firends("a", "祝天长地久");
Firends f2 = new Firends("b", "祝白头到老");
Firends f3 = new Firends("c", "祝早生贵子");
XiaoWang.eMarry += new EventHandler(f1.ShowWish);
XiaoWang.eMarry += new EventHandler(f2.ShowWish);
XiaoWang.eMarry += new EventHandler(f3.ShowWish);
Console.WriteLine("小王的朋友都早早准备好了礼物");
Console.WriteLine("现在小王要结婚了");
XiaoWang.Marry();
Console.Read();
}
}
public class XiaoWang
{
public static event EventHandler eMarry;
public XiaoWang()
{
}
public static void Marry()
{
Console.WriteLine("小王要结婚了\\(^o^)/~");
if (eMarry != null)
{
eMarry(null, null);
}
}
}
public class Firends
{
public string Name { get; set; }
public string Wish { get; set; }
public Firends(string name, string wish)
{
this.Name = name;
this.Wish = wish;
}
public void ShowWish(object sender, EventArgs e)
{
Console.WriteLine(Name + ":" + Wish);
}
}
}
2.
using System;
namespace baiduDemo
{
class Program2
{
static void Main(string[] args)
{
Cat cat = new Cat("老鼠洞旁边");
Mouse mouse = new Mouse();
mouse.Run += new EventHandler(cat.CatchMouse);
Console.WriteLine("There is a cat:" + cat.Postion + ",waiting...");
Console.WriteLine("A mouse will run out");
mouse.RunOut();
Console.Read();
}
}
public class Mouse
{
public event EventHandler Run;
public Mouse()
{
}
public void RunOut()
{
Console.WriteLine("A mouse run out.");
if (Run != null)
{
Run(null, null);//简化
}
}
}
public class Cat
{
private string postion;
public string Postion
{
get { return postion; }
}
public Cat(string postion) { this.postion = postion; }
public void CatchMouse(object sender, EventArgs e)
{
Console.WriteLine("The cat catch the mouse.");
}
}
}
总结:
委托的作用:
占位,在不知道将来要执行的方法的具体代码时,可以先用一个委托变量来代替方法调用(委托的返回值,参数列表要确定)。在实际调用之前,需要为委托赋值。
事件的作用:
与委托变量一样,只是功能上比委托变量有更多的限制。(比如:1.只能通过+=或-=来绑定方法(事件处理程序)2.只能在类内部调用(触发)事件。)