委托可以看做类型 ,事件就是类型的实例;
定义一个EventNavigate类:
class EventNavigate { //自定义委托 public delegate void My(object sender, int arg); //声明事件 public event My myEvent; //声明带有参数事件 public event Action<int> actionEventWithParam; //声明没有参数事件 public event Action actionEventNotParam; /// <summary> /// 声明没有参数带有返回值事件 /// </summary> public event Func<int> funcEvent; //声明带有参数而且有返回值事件 public event Func<int,string> funcEventReturn; public void MyEvent(int i) { if (this.myEvent != null) { this.myEvent(this, i * 5); } } public void ActionEventWithParam(int i) { if (this.actionEventWithParam != null) { this.actionEventWithParam(i * 5); } } public void ActionEventWithParam() { if (this.actionEventNotParam != null) { this.actionEventNotParam(); } } public void FuncEvent() { if (funcEvent != null) { int result= funcEvent(); Console.WriteLine("***************"+result); } } public void FuncEventReturn(int i) { if (funcEventReturn != null) { string result= funcEventReturn(i); Console.WriteLine("***************" + result+"***************"); } } }调用代码:
static void Main(string[] args) { EventNavigate eventN = new EventNavigate(); eventN.myEvent += (sender,e) => { Console.WriteLine("myEvent->sender name:"+sender.GetType().Name+" result::"+e); }; eventN.MyEvent(10); eventN.actionEventWithParam += (obj) => { Console.WriteLine("actionEventWithParamresult ::" + obj); }; eventN.ActionEventWithParam(10); eventN.actionEventNotParam+=()=>{ Console.WriteLine("actionEventNotParam ::" ); }; eventN.ActionEventWithParam(); eventN.funcEvent += () => { return 250; }; eventN.FuncEvent(); eventN.funcEventReturn += (i) => { return 250 * i + ""; }; eventN.FuncEventReturn(20); Console.ReadKey(); }