★要为类构造一个事件,必须用event来声...... 要为类构造一个事件,必须用 event 来声明一个 delegate 型的字段,如: puclic calss Test{ public delegate EventHandler(object sender, EventArgs e); //声明为delegate 型的事件; } 然后要指定一个事件的名称,并写出处理语句: public event EventHandler Load 在创建类的实例后定义这个 “Load”事件: Test m=new Test(); m.load=new EventHandler(m_Load); void m_Load(object sender, EventArgs e) { MessageBox.Show(" this is a class event"); } 再看看下面的完整的一段代码: using System; class TestClass { static void Main(string[] args) { EventClass myEventClass = new EventClass(); myEventClass.CustomEvent += new EventClass.CustomEventHandler(CustomEvent1); // 关联事件句柄; myEventClass.CustomEvent += new EventClass.CustomEventHandler(CustomEvent2); myEventClass.InvokeEvent(); myEventClass.CustomEvent -= new EventClass.CustomEventHandler(CustomEvent2); myEventClass.InvokeEvent(); myEventClass.Load += new EventClass.CustomEventHandler(Load1); myEventClass.onLoad(); } private static void CustomEvent1(object sender, EventArgs e) { Console.WriteLine("Fire Event 1"); } private static void CustomEvent2(object sender, EventArgs e) { Console.WriteLine("Fire Event 2"); } private static void Load1(object sender, EventArgs e) { Console.WriteLine("Current background color is {0}. Please input:", System.Console.BackgroundColor.ToString()); } } public class EventClass { public delegate void CustomEventHandler(object sender, EventArgs e);//首先定义一个委托类型的对象CustomEventHandler //用delegate数据类型声明事件,要用event关键字,这里定义了两个字件; public event CustomEventHandler CustomEvent; public event CustomEventHandler Load; public void InvokeEvent() { CustomEvent(this, EventArgs.Empty); } public void onLoad() { Console.BackgroundColor = ConsoleColor.Red; Load(this, EventArgs.Empty); string s = Console.ReadLine(); if (s != "yuping") { Console.WriteLine("You must type 'yuping' for change it !"); } else { Console.BackgroundColor = System.ConsoleColor.Black; Console.Clear(); } } } 在包含事件声明的类中,声明一个数据类型是委托的这么样的一个对象CustomEventHandler, 它有两个参数(sender和e);在这里使用委托的目的就是在运行中向参数传递方法,并由委托对象生成的实例接收这个参数方法的返回值,因此,在声明委托型的对象时应根据类中的方法结构来定义,或者说在引用类中应当根据委托型对象的结构来生成响应事件的方法结构,比如两者都有哪些类型的参数、返回值的类型,也就是说两者要保持一致。同时,要正确地使用C#中的委托,就必须保持三个步骤:声明——实例化——调用。 在上面的代码中,EventClass 类就体现了这个原则: 1. 声明委托类型的对象: public delegate void CustomEventHandler(object sender, EventArgs e); 2. 创建CustomEventHandler对象的实例CustomEvent:public event CustomEventHandler CustomEvent; 3. 在InvokeEvent()方法中实现了对该事件的调用,引用事件。 |
|小黑屋|最新主题|手机版|微赢网络技术论坛 ( 苏ICP备08020429号 )
GMT+8, 2024-9-30 05:34 , Processed in 0.136765 second(s), 12 queries , Gzip On, MemCache On.
Powered by Discuz! X3.5
© 2001-2023 Discuz! Team.