using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;namespace ConsoleApplication34{ class Program { static void Main(string[] args) { Heater h = new Heater(); alertM a = new alertM(); h.BoilEvent += a.AM; h.Boiled(); Console.ReadLine(); } } public delegate void BoilHandler(object sender,BoilEventArgs e); public class Heater { public int temperature; public event BoilHandler BoilEvent; public void Boiled() { for (int i = 0; i <= 100; i++) { temperature = i; if (temperature > 95) { BoilEvent(this, new BoilEventArgs(temperature)); Thread.Sleep(2000); } } } } public class alertM { public void AM(object sender,BoilEventArgs e) { Console.WriteLine("水马上就要开了"+e.temperature); } } public class BoilEventArgs : EventArgs { public int temperature; public BoilEventArgs(int param) { temperature = param; } }}
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication35{ class Program { static void Main(string[] args) { Listlist1 = new List (); User u1 = new User("Daniel"); User u2 = new User("Acadia"); User u3 = new User("Johnes"); list1.Add(new User("Daniel")); list1.Add(u2); list1.Add(u3); ChangeName cn = new ChangeName(list1); cn.RenameEvent += cn.RE; cn.Rename("testtest", 2); Console.ReadLine(); } } public class User { public string Name; public User(string name) { Name = name; } } public class ChangeName { List listuser; public delegate void RenameHandler(object sender, RenameEventArgs e); public event RenameHandler RenameEvent; public ChangeName(List list) { listuser = list; } public void Rename(string NewName,int i) { if (i < listuser.Count && i>0) { string OldName = listuser[i].Name; listuser[i].Name = NewName; RenameEvent(this, new RenameEventArgs(OldName,NewName,i)); } } public void RE(object sender,RenameEventArgs e) { Console.WriteLine("第" + e.Order+"项,用户名称已经由" + e.OldName + "改为了 " + e.NewName); } } public class RenameEventArgs : EventArgs { public string NewName; public string OldName; public int Order; public RenameEventArgs(string Oldparam,string Newparam,int i) { OldName = Oldparam; NewName = Newparam; Order = i; } }}
备注:事件委托要放在事件发生的前面,如下:
h.BoilEvent += a.AM;
h.Boiled();参考链接:
关于事件和委托,这篇写的太好了: