關於c#中的事件,
原文鏈接http://blog.csdn.net/joyhen/article/details/8500211
最近在看委托,然後看到事件,以前一直很模糊,關於事件的觸發者和響應者的關聯。貼一個簡單的例子:
1.新建一個類Control.cs
- using System;
-
- namespace EventComplex
- {
- /*
- * C#中的事件處理實際上是一種具有特殊簽名的delegate
- */
- public class Control
- {
- /// <summary>
- /// 代表事件發送者
- /// </summary>
- /// <param name="sender">代表事件發送者</param>
- /// <param name="e">事件參數類
- /// <remarks>用來包含與事件相關的數據,所有的事件參數類都必須從System.EventArgs類派生</remarks>
- /// </param>
- public delegate void MyEventHandler(object sender, MyEventArgs e);//System.EventArgs e
- public event MyEventHandler MyEvent;
-
- public Control()
- {
- this.MyEvent += new MyEventHandler(RaiseSomeEvent);
- }
-
- /// <summary>
- /// 一個事件
- /// </summary>
- public void RaiseSomeEvent(object sender, MyEventArgs e)
- {
- Console.WriteLine("hello " + e.ParamName);
- Console.ReadLine();
- }
-
- public void RiseSomeEvent()
- {
- //System.EventArgs e = new System.EventArgs();
- Console.Write("Please input 'Name':");
- string _param = Console.ReadLine();//ReadLine:按下回車以後才讀取,然後觸發MyEvent事件
-
- //if (_param.Equals("jon"))//在用戶輸入jon的情況下觸發事件,否則不觸發
- MyEvent(this, new MyEventArgs(_param));//MyEvent(this,e)
- }
- }
-
- public class MyEventArgs : System.EventArgs
- {
- public string ParamName;
- public MyEventArgs(string _name)
- {
- ParamName = _name;
- }
- }
- }
2.我們去Main函數裡面測試一下;
- public static void demo4()
- {
- Control ctr = new Control();
- ctr.MyEvent += new Control.MyEventHandler(ResponseSomeEvent);
- ctr.RiseSomeEvent();
- }
- public static void ResponseSomeEvent(object sender, EventArgs e)
- {
- Console.WriteLine("Some event occur!");
- }
- static void Main(string[] args)
- {
- demo4();
- }