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