c#在程序中定義和使用自定義事件方法總結
更新時間:2019年03月11日 08:38:34 投稿:laozhang
在本篇文章中小編給大家整理了關于c#在程序中定義和使用自定義事件方法總結相關知識點,需要的朋友們學習下。
C#在程序中定義和使用自定義事件可以分為以下幾個步驟:
步驟1:在類中定義事件
using System; public class TestClass { //.... public event EventHandler TestEvent }
步驟2:定義事件參數(shù)
注意:事件參數(shù)類TestEventArgs繼承自System.EventArgs
using System; public class TestEventArgs : EventArgs { public TestEventArgs() : base() { } public string Message { get; set; } }
步驟3:在TestClass 引發(fā)事件
public class TestClass { // 這個方法引發(fā)事件 public void RaiseTestEvent(string message) { if (TestEvent == null) return; TestEvent(this, new TestEventArgs { Message = message }); } public event EventHandler TestEvent; }
步驟4:使用事件
class Program { static void Main(string[] args) { TestClass tc = new TestClass(); // 掛接事件處理方法 tc.TestEvent += Tc_TestEvent; Console.WriteLine("按任意鍵引發(fā)事件"); Console.ReadKey(); // 引發(fā)事件 tc.RaiseTestEvent("通過事件參數(shù)傳遞的字符串"); Console.WriteLine("按任意鍵退出"); Console.ReadKey(); } private static void Tc_TestEvent(object sender, EventArgs e) { // 將事件參數(shù)強制轉換為TestEventArgs TestEventArgs te = (TestEventArgs)e; // 顯示事件參數(shù)中的Message Console.WriteLine(te.Message); } }
完整的程序如下
using System; public class TestClass { public void RaiseTestEvent(string message) { if (TestEvent == null) return; TestEvent(this, new TestEventArgs { Message = message }); } public event EventHandler TestEvent; } public class TestEventArgs : EventArgs { public TestEventArgs() : base() { } public string Message { get; set; } } class Program { static void Main(string[] args) { TestClass tc = new TestClass(); tc.TestEvent += Tc_TestEvent; Console.WriteLine("按任意鍵引發(fā)事件"); Console.ReadKey(); tc.RaiseTestEvent("通過事件參數(shù)傳遞的字符串"); Console.WriteLine("按任意鍵退出"); Console.ReadKey(); } private static void Tc_TestEvent(object sender, EventArgs e) { TestEventArgs te = (TestEventArgs)e; Console.WriteLine(te.Message); } }
相關文章
Unity的BuildPlayerProcessor實用案例深入解析
這篇文章主要為大家介紹了Unity的BuildPlayerProcessor實用案例深入解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05DevExpress實現(xiàn)自定義GridControl中按鈕文字內(nèi)容的方法
這篇文章主要介紹了DevExpress實現(xiàn)自定義GridControl中按鈕文字內(nèi)容的方法,需要的朋友可以參考下2014-08-08