Home Backend Development C#.Net Tutorial How to define and use custom events in c#

How to define and use custom events in c#

Mar 09, 2019 pm 04:50 PM
Custom events

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.

How to define and use custom events in c#

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Creating and Applying Custom Attributes in C# Creating and Applying Custom Attributes in C# Jul 07, 2025 am 12:03 AM

CustomAttributes are mechanisms used in C# to attach metadata to code elements. Its core function is to inherit the System.Attribute class and read through reflection at runtime to implement functions such as logging, permission control, etc. Specifically, it includes: 1. CustomAttributes are declarative information, which exists in the form of feature classes, and are often used to mark classes, methods, etc.; 2. When creating, you need to define a class inherited from Attribute, and use AttributeUsage to specify the application target; 3. After application, you can obtain feature information through reflection, such as using Attribute.GetCustomAttribute();

Designing Immutable Objects and Data Structures in C# Designing Immutable Objects and Data Structures in C# Jul 15, 2025 am 12:34 AM

The core of designing immutable objects and data structures in C# is to ensure that the state of the object is not modified after creation, thereby improving thread safety and reducing bugs caused by state changes. 1. Use readonly fields and cooperate with constructor initialization to ensure that the fields are assigned only during construction, as shown in the Person class; 2. Encapsulate the collection type, use immutable collection interfaces such as ReadOnlyCollection or ImmutableList to prevent external modification of internal collections; 3. Use record to simplify the definition of immutable model, and generate read-only attributes and constructors by default, suitable for data modeling; 4. It is recommended to use System.Collections.Imm when creating immutable collection operations.

Handling Large Datasets Efficiently with C# Handling Large Datasets Efficiently with C# Jul 06, 2025 am 12:10 AM

When processing large amounts of data, C# can be efficient through streaming, parallel asynchronous and appropriate data structures. 1. Use streaming processing to read one by one or in batches, such as StreamReader or EFCore's AsAsyncEnumerable to avoid memory overflow; 2. Use parallel (Parallel.ForEach/PLINQ) and asynchronous (async/await Task.Run) reasonably to control the number of concurrency and pay attention to thread safety; 3. Select efficient data structures (such as Dictionary, HashSet) and serialization libraries (such as System.Text.Json, MessagePack) to reduce search time and serialization overhead.

Writing Maintainable and Testable C# Code Writing Maintainable and Testable C# Code Jul 12, 2025 am 02:08 AM

The key to writing C# code well is maintainability and testability. Reasonably divide responsibilities, follow the single responsibility principle (SRP), and take data access, business logic and request processing by Repository, Service and Controller respectively to improve structural clarity and testing efficiency. Multi-purpose interface and dependency injection (DI) facilitate replacement implementation, extension of functions and simulation testing. Unit testing should isolate external dependencies and use Mock tools to verify logic to ensure fast and stable execution. Standardize naming and splitting small functions to improve readability and maintenance efficiency. Adhering to the principles of clear structure, clear responsibilities and test-friendly can significantly improve development efficiency and code quality.

Benchmarking and Profiling C# Code Performance Benchmarking and Profiling C# Code Performance Jul 03, 2025 am 12:25 AM

C# code performance optimization requires tools rather than intuition. BenchmarkDotNet is the first choice for benchmarking. 1. Automatically handle JIT warm-up and GC effects by scientifically comparing the execution efficiency of different methods; 2. Profiling using tools such as VisualStudio, dotTrace or PerfView to find the truly time-consuming "hot spot" functions; 3. Pay attention to memory allocation, combine [MemoryDiagnoser], DiagnosticTools and PerfView to analyze GC pressure, reduce object creation in high-frequency paths, and give priority to using structures or pooling technology to reduce GC burden.

Creating Custom Middleware in ASP.NET Core C# Creating Custom Middleware in ASP.NET Core C# Jul 11, 2025 am 01:55 AM

Create custom middleware in ASP.NETCore, which can be implemented by writing classes and registering. 1. Create a class containing the InvokeAsync method, handle HttpContext and RequestDelegatenext; 2. Register with UseMiddleware in Program.cs. Middleware is suitable for general operations such as logging, performance monitoring, exception handling, etc. Unlike MVC filters, it acts on the entire application and does not rely on the controller. Rational use of middleware can improve structural flexibility, but should avoid affecting performance.

Best Practices for Using LINQ in C# Effectively Best Practices for Using LINQ in C# Effectively Jul 09, 2025 am 01:04 AM

The following points should be followed when using LINQ: 1. Priority is given to LINQ when using declarative data operations such as filtering, converting or aggregating data to avoid forced use in scenarios with side effects or performance-critical scenarios; 2. Understand the characteristics of delayed execution, source set modifications may lead to unexpected results, and delays or execution should be selected according to requirements; 3. Pay attention to performance and memory overhead, chain calls may generate intermediate objects, and performance-sensitive codes can be replaced by loops or spans; 4. Keep the query concise and easy to read, and split complex logic into multiple steps to avoid excessive nesting and mixing of multiple operations.

Deep Dive into C# Generics Constraints and Covariance Deep Dive into C# Generics Constraints and Covariance Jul 12, 2025 am 02:00 AM

Generic constraints are used to restrict type parameters to ensure specific behavior or inheritance relationships, while covariation allows subtype conversion. For example, whereT:IComparable ensures that T is comparable; covariation such as IEnumerable allows IEnumerable to be converted to IEnumerable, but it is only read and cannot be modified. Common constraints include class, struct, new(), base class and interface, and multiple constraints are separated by commas; covariation requires the out keyword and is only applicable to interfaces and delegates, which is different from inverter (in keyword). Note that covariance does not support classes, cannot be converted at will, and constraints affect flexibility.

See all articles