C#中的事件机制
这几天把事件学了一下,总算明白了一些。不多说了,直接代码。
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 CatAndMouse h = new CatAndMouse(); 6 h.catDog += (new Mouse()).RunCat; 7 h.PlayCat(); 8 Console.ReadKey(); 9 10 11 } 12 public class Mouse 13 { 14 public void RunCat(object sender, ConsoleApplication1.CatAndMouse.CatEventArgs e) 15 { 16 Console.WriteLine("老鼠吃了"+e.cat.CatName+e.cat.CatCount+"次"); 17 } 18 } 19 20 } 21 //定义一个类,声明猫的属性 22 #region 类 23 public class Cat 24 { 25 private string catName; 26 27 public string CatName 28 { 29 get { return catName; } 30 set { catName = value; } 31 } 32 private int catCount; 33 34 public int CatCount 35 { 36 get { return catCount; } 37 set { catCount = value; } 38 } 39 } 40 #endregion 41 42 public class CatAndMouse 43 { 44 public delegate void CatEventHandler(object sender, CatEventArgs e); //定义委托 45 public event CatEventHandler catDog; //声明事件变量 46 public class CatEventArgs : EventArgs //声明事件参数,可以把参数传递过去 47 { 48 public Cat cat = new Cat(); 49 public CatEventArgs(string catName, int count) 50 { 51 this.cat.CatCount = count; 52 this.cat.CatName = catName; 53 } 54 55 } 56 //可以供继承自 CatAndMouse 的类重写,以便继承类拒绝其他对象对它的监视 57 protected virtual void catdo(CatEventArgs e) 58 { 59 if (catDog != null) //如果对象类不为空,则可以调用注册的方法 60 { 61 catDog(this, e); //把参数传递过去 62 } 63 } 64 public void PlayCat() 65 { 66 CatEventArgs c = new CatEventArgs("哈哈", 2); 67 catdo(c); //调用方法 68 } 69 70 }