| using System; file://步骤1: 声明一个委托对象 public delegate void MyDelegate(string input); file://步骤2::定义各个方法,其参数形式和步骤1中声明的委托对象的必须相同 class MyClass1{ public void delegateMethod1(string input){ Console.WriteLine( "This is delegateMethod1 and the input to the method is {0}", www.hot007.com input); } public void delegateMethod2(string input){ Console.WriteLine( "This is delegateMethod2 and the input to the method is {0}", input); } } file://步骤3:创建一个委托对象并将上面的方法包含其中 class MyClass2{ public MyDelegate createDelegate(){ MyClass1 c2=new MyClass1(); MyDelegate d1 = new MyDelegate(c2.delegateMethod1); MyDelegate d2 = new MyDelegate(c2.delegateMethod2); MyDelegate d3 = d1 d2; return d3; } } file://步骤4:通过委托对象调用包含在其中的方法 class MyClass3{ public void callDelegate(MyDelegate d,string input){ d(input); } } class Driver{ static void Main(string[] args){ MyClass2 c2 = new MyClass2(); MyDelegate d = c2.createDelegate(); MyClass3 c3 = new MyClass3(); c3.callDelegate(d,"Calling the delegate"); } } |
www.hot007.com
| public delegate void MyEventHandler(object sender, MyEventArgs e); |
| public class MyEventArgs EventArgs{ public string m_myEventArgumentdata; } |
| public event MyEventHandler MyEvent; |
| using System; file://步骤1:声明委托对象 public delegate void MyHandler1(object sender,MyEventArgs e); public delegate void MyHandler2(object sender,MyEventArgs e); file://步骤2:创建事件处理函数的方法 class A{ public const string m_id="Class A"; public void OnHandler1(object sender,MyEventArgs e){ Console.WriteLine("I am in OnHandler1 and MyEventArgs is {0}", hot007.com e.m_id); } public void OnHandler2(object sender,MyEventArgs e){ Console.WriteLine("I am in OnHandler2 and MyEventArgs is {0}", e.m_id); } file://步骤3:创建委托对象,并事件处理函数包含在其中同时设置好将要触发事件的对象 public A(B b){ MyHandler1 d1=new MyHandler1(OnHandler1); MyHandler2 d2=new MyHandler2(OnHandler2); b.Event1 =d1; b.Event2 =d2; } } file://步骤4:通过委托对象(也就是触发事件)来调用被包含的方法 class B{ public event MyHandler1 Event1; public event MyHandler2 Event2; public void FireEvent1(MyEventArgs e){ if(Event1 != null){ Event1(this,e); } Tags:浅析Visual,C#事件处理机制
上一篇:EVC开发实例之保存信息(二) 下一篇:C++计算四则表达式的模板
您的评论·用户发表意见仅代表其个人意见,并且承担一切因发表内容引起的纠纷和责任
·本站管理人员有权在不通知用户的情况下删除不符合规定的评论信息或留做证据 ·请客观的评价您所看到的资讯,提倡就事论事,杜绝漫骂和人身攻击等不文明行为 精彩推荐最新资讯 |