事件与委托,终于明白了


using
System; using System.Threading; namespace DelegateEvents { class Program { static void Main(string[] args) { Tostring To = new Tostring(); Target tr = new Target(); To.Myevent += tr.Alert;//注册方法,执行具体功能在里面写,主要部分就是在此方法了 To.Myevent += tr.Alert2;//注册方法,执行具体功能在里面写,主要部分就是在此方法了 To.Mes();//执行事件 Console.ReadKey(); } } class Tostring { public delegate void Mydel(int Myint);//定义一个委托,和类同级 public event Mydel Myevent;//定义委托的事件 public int i; /// <summary> /// 事件执行函数 /// </summary> public void Mes()//定义一个方法执行事件 { for (int j = 0; j < 100; j++) { i = j; if (i>10) { if (Myevent!=null) { Myevent(i); Thread.Sleep(1000); } } } } } /// <summary> /// 事件调用函数,参数要与委托参数一致 /// </summary> class Target { public void Alert(int j)//参数j为事件的i传过来的 { if(j>10) Console.WriteLine("水温{0}",j); } public void Alert2(int j) { if(j>98) Console.WriteLine("水温{0},马上开了", j); } } }

猜你喜欢

转载自www.cnblogs.com/Maxs/p/9157352.html
今日推荐