事件是一种特殊的委托,只能在类的内部进行+=或 -=操作
为什么我们要用事件,比如
class Cat { private string CatName; private string Catcolor; public Cat(string CatName, string Catcolor) { this.CatName = CatName; this.Catcolor = Catcolor; } public void CatComing () { Console.WriteLine(Catcolor+"的"+CatName + "进来了"); if(Catcome!=null) Catcome(); } public Action Catcome; } class Mouth { private string Name; private string color; public Mouth(string Name, string color,Cat cat) { this.Name = Name; this.color = color; cat.Catcome += this.mouthcoming; } public void mouthcoming() { Console.WriteLine(color + "的" + Name + "说快跑"); } } class Program { static void Main(string[] args) { Cat cat = new Cat("加菲猫","黄色的"); Mouth mouth1 = new Mouth("米老鼠", "黑色的",cat); cat.CatComing(); cat.Catcome();//这里可以对Catcome委托进行调用,程序的耦合性提高会有危险 Console.ReadKey(); } }
为了降低程序的耦合性,将public Action Catcome;声明为事件public event Action Catcome;
public Action Catcome;