你的位置:首页 > ASP.net教程

[ASP.net教程]关于c#中的事件解读


static void Main(string[] args) 02.    { 03.      demo4(); 04.    } 

 

1.新建一个类Control.cs

using System; 02. 03.namespace EventComplex 04.{ 05.  /* 06.   * C#中的事件处理实际上是一种具有特殊签名的delegate 07.   */ 08.  public class Control 09.  { 10.    /// <summary> 11.    /// 代表事件发送者 12.    /// </summary> 13.    /// <param name="sender">代表事件发送者</param> 14.    /// <param name="e">事件参数类 15.    /// <remarks>用来包含与事件相关的数据,所有的事件参数类都必须从System.EventArgs类派生</remarks> 16.    /// </param> 17.    public delegate void MyEventHandler(object sender, MyEventArgs e);//System.EventArgs e 18.    public event MyEventHandler MyEvent; 19. 20.    public Control() 21.    { 22.      this.MyEvent += new MyEventHandler(RaiseSomeEvent); 23.    } 24. 25.    /// <summary> 26.    /// 一个事件 27.    /// </summary> 28.    public void RaiseSomeEvent(object sender, MyEventArgs e) 29.    { 30.      Console.WriteLine("hello " + e.ParamName); 31.      Console.ReadLine(); 32.    } 33. 34.    public void RiseSomeEvent() 35.    { 36.      //System.EventArgs e = new System.EventArgs(); 37.      Console.Write("Please input 'Name':"); 38.      string _param = Console.ReadLine();//ReadLine:按下回车以后才读取,然后触发MyEvent事件 39. 40.      //if (_param.Equals("jon"))//在用户输入jon的情况下触发事件,否则不触发  41.      MyEvent(this, new MyEventArgs(_param));//MyEvent(this,e) 42.    } 43.  } 44. 45.  public class MyEventArgs : System.EventArgs 46.  { 47.    public string ParamName; 48.    public MyEventArgs(string _name) 49.    { 50.      ParamName = _name; 51.    } 52.  } 53.} 

 我们去Main函数里面测试一下;

public static void demo4() 02.    { 03.      Control ctr = new Control(); 04.      ctr.MyEvent += new Control.MyEventHandler(ResponseSomeEvent); 05.      ctr.RiseSomeEvent(); 06.    } 07.    public static void ResponseSomeEvent(object sender, EventArgs e) 08.    { 09.      Console.WriteLine("Some event occur!"); 10.    }