定义一个猫类
public class Cat
{
private string name;
public Cat(String name)
{
this.name=name;
}
//定义一个委托
public delegate void CatShoutEventHandler();
//定义一个事件
public event CatShoutEventHandler CatShout;
public void Shout()
{
Console.WriteLine("喵,我是猫{0}",this.name);
if(CatShout!=null)
{
CatShout();
}
}
}
定义一个老鼠类
public class Mouse
{
private string name;
public Mouse(String name)
{
this.name=name;
}
public void Run()
{
Console.WriteLine("我是老鼠{0},猫来了,快跑啊!");
}
}
public class Program
{
void Main(string[] args)
{
Cat cat1=new Cat("猫1");
Mouse mouse1=new Mouse("老鼠一");
Mouse mouse2=new Mouse("老鼠二");
//订阅事件
cat1.CatShout+=new Cat.CatShoutEventHander(mouse1.Run);
cat1.CatShout+=new Cat.CatShoutEventHander(mouse2.Run);
cat1.Shout();
}
}