Home>Article>Backend Development> How to define and use custom events in c#
C# How to define and use custom events in the program: first define the event in the class; then define the parameters of the event; then trigger the event in TestClass; and finally use the event.
C#The steps to define and use custom events in the program are: first define the event in the class, and then define the parameters of the event in TestClass Trigger the event and finally use the event
[Recommended course:C# tutorial]
C# Defining and using custom events in the program can be divided into the following Several steps:
Step 1: Define the event in the class
using System; public class TestClass { //.... public event EventHandler TestEvent }
Step 2: Define the event parameters
Note : Event parameter class TestEventArgs inherits from System.EventArgs
using System; public class TestEventArgs : EventArgs { public TestEventArgs() : base() { } public string Message { get; set; } }
Step 3: Raise event in TestClass
public class TestClass { // 这个方法引发事件 public void RaiseTestEvent(string message) { if (TestEvent == null) return; TestEvent(this, new TestEventArgs { Message = message }); } public event EventHandler TestEvent; }
Step 4: Use event
class Program { static void Main(string[] args) { TestClass tc = new TestClass(); // 挂接事件处理方法 tc.TestEvent += Tc_TestEvent; Console.WriteLine("按任意键引发事件"); Console.ReadKey(); // 引发事件 tc.RaiseTestEvent("通过事件参数传递的字符串"); Console.WriteLine("按任意键退出"); Console.ReadKey(); } private static void Tc_TestEvent(object sender, EventArgs e) { // 将事件参数强制转换为TestEventArgs TestEventArgs te = (TestEventArgs)e; // 显示事件参数中的Message Console.WriteLine(te.Message); } }
The complete program is as follows
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("按任意键引发事件"); Console.ReadKey(); tc.RaiseTestEvent("通过事件参数传递的字符串"); Console.WriteLine("按任意键退出"); Console.ReadKey(); } private static void Tc_TestEvent(object sender, EventArgs e) { TestEventArgs te = (TestEventArgs)e; Console.WriteLine(te.Message); } }
Summary: The above is the entire content of this article, I hope it will be helpful to everyone.
The above is the detailed content of How to define and use custom events in c#. For more information, please follow other related articles on the PHP Chinese website!