浅析C#的事件处理和自定义事件
一、簡單的自定義事件(1):無參數
namespace UserInputMonitor
{
??? class UserInputMonitor
??? {
??????? public delegate void UserRequest(object sender, EventArgs e);
??????? //定義委托
??????? public event UserRequest OnUserRequest;
??????? //此委托類型類型的事件
????? ??public void Run()
??????? {
??????????? bool finished = false;
??????????? do
??????????? {
??????????????? if (Console.ReadLine() == "h")
??????????????? {
??????????????????? OnUserRequest(this, new EventArgs());
??????????????? }
??????????????? else if (Console.ReadLine() == "e")
??????????????? {
??????????????????? finished = true;
??????????????? }
??????????? } while (!finished);
??????? }
??? }
??? public class Client
??? {
??????? public static void Main()
??????? {
??????????? UserInputMonitor monitor = new UserInputMonitor();
??????????? new Client(monitor);
??????????? monitor.Run();
??????? }
??????? private void ShowMessage(object sender, EventArgs e)
??????? {
??????????? Console.WriteLine("HaHa!!");
??????? }
??????? Client(UserInputMonitor m)
??????? {
??????????? m.OnUserRequest += new UserInputMonitor.UserRequest(this.ShowMessage);
??????????? //m.OnUserRequest+=new m.UserRequest(this.ShowMessage);
??????????? //注意這種寫法是錯誤的,因為委托是靜態的
??????? }
??? }
}
二、簡單的自定義事件(2):包含參數
class MyEventArgs:EventArgs
{
??? private string keyChars;
???
??? public MyEventArgs(string keyChars)
??? {
??????? this.keyChars = keyChars;
??? }
???
??? public string KeyChars
??? {
??????? get
??????? {
??????????? return keyChars;
??????? }
??? }
}
class UserInputMonitor
{
??? //定義委托
??? public delegate void UserRequest(object sender,MyEventArgs e);
??? //此委托類型類型的事件,用戶累加客戶端事件
??? public event UserRequest OnUserRequest;
??? public void Run() //定義此事件激發的條件
??? {
??????? bool finished=false;
??????? do
??????? {
?????????? string inputString= Console.ReadLine();
?????????? if (inputString != "")
?????????????? OnUserRequest(this, new MyEventArgs(inputString));
?????????? else
?????????????? finished = true;
??????? }while(!finished);
???? }
}
public class Client
{
???? public static void Main()
???? {
????????? UserInputMonitor monitor=new UserInputMonitor();
????????? new Client(monitor);
????????? monitor.Run();
???? }
???? private void ShowMessage(object sender,MyEventArgs e)
???? {
????????? Console.WriteLine("捕捉到:{0}",e.KeyChars);
???? }
???? Client(UserInputMonitor m)
???? {
????????? m.OnUserRequest+=new UserInputMonitor.UserRequest(this.ShowMessage);
????????? //m.OnUserRequest+=new m.UserRequest(this.ShowMessage);
????????? //注意這種寫法是錯誤的,因為委托是靜態的
???? }
}
轉載于:https://www.cnblogs.com/qqhfeng/archive/2010/02/26/1674102.html
總結
以上是生活随笔為你收集整理的浅析C#的事件处理和自定义事件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用C#做短信CMPP2.0/3.0协议
- 下一篇: c# char unsigned_dll