Delegate and Event in C#. Delegates and events are very important features in C#. They allow you to implement callback mechanisms and publish-subscribe modes, thereby improving code flexibility and decoupling. By using delegates and events, you can write more modular and scalable applications. Here is an article about delegations and events in C#.
introduction
Delegate and Event are very important features in C#. They allow you to implement callback mechanisms and publish-subscribe modes, thereby improving code flexibility and decoupling. By using delegates and events, you can write more modular and scalable applications. This article will introduce in detail the delegations and events in C#, including their basic concepts, usage methods and application scenarios.
The basic concept of commission
What is delegation?
Delegates are type-safe function pointers that allow you to pass methods as arguments to other methods. Delegates define a method signature, and any method that matches the signature can be referenced by the delegate instance.
Definition Delegation
Can be passeddelegate
Keywords to define the delegate type.
public delegate void NotifyHandler(string message);
Use Delegate
Once a delegate is defined, fields or properties of the delegate type can be declared in the class and delegate is called if needed.
public class Notifier { public event NotifyHandler OnNotify; public void TriggerNotification(string message) { OnNotify?.Invoke(message); // Call all subscribers } } public class Subscriber { public Subscriber(Notifier notifier) { += HandleNotification; } private void HandleNotification(string message) { ($"Received notification: {message}"); } } // Use the Delegatevar notifier = new Notifier(); var subscriber = new Subscriber(notifier); ("Hello, World!");
Built-in delegate type
C# provides some built-in delegate types, such asAction
andFunc
, They simplify common delegate definitions.
Action Delegation
Action
is a delegate without a return value and can accept multiple input parameters.
Action<string> printAction = ; printAction("Hello, World!");
Func Delegation
Func
is a delegate with a return value that can accept multiple input parameters.
Func<int, int, int> addFunc = (a, b) => a + b; (addFunc(3, 5)); // Output: 8
The basic concept of events
What is an event?
An event is a special delegate that allows an object to notify other objects that something has happened. Events are often used to implement publish-subscribe mode, making the code more decoupled and modular.
Define events
Events are defined based on delegate type, usually usedevent
Keywords are declared.
public class Publisher { public event EventHandler<EventArgs> SomethingHappened; protected virtual void OnSomethingHappened() { SomethingHappened?.Invoke(this, ); } public void DoSomething() { // Simulate something happening OnSomethingHappened(); } } public class Subscriber { public Subscriber(Publisher publisher) { += Publisher_SomethingHappened; } private void Publisher_SomethingHappened(object sender, EventArgs e) { ("Something happened!"); } } //User eventsvar publisher = new Publisher(); var subscriber = new Subscriber(publisher); (); // Trigger event
Custom event parameters
To pass more information, you can create a custom event parameter class, inherit fromEventArgs
。
public class CustomEventArgs : EventArgs { public string Message { get; set; } } public class Publisher { public event EventHandler<CustomEventArgs> SomethingHappened; protected virtual void OnSomethingHappened(CustomEventArgs e) { SomethingHappened?.Invoke(this, e); } public void DoSomething(string message) { OnSomethingHappened(new CustomEventArgs { Message = message }); } } public class Subscriber { public Subscriber(Publisher publisher) { += Publisher_SomethingHappened; } private void Publisher_SomethingHappened(object sender, CustomEventArgs e) { ($"Publisher says: {}"); } } // Use custom event parametersvar publisher = new Publisher(); var subscriber = new Subscriber(publisher); ("Hello, World!"); // Trigger events and pass information
Application scenarios
User interface interaction
Events are widely used in communication between user interface components, such as button clicks, text box input, etc.
+= (sender, e) => ("Button clicked!");
Data binding
Events can be used for data binding, triggering updates when the data source changes.
+= (sender, e) => UpdateUI();
Logging
Events can be used to implement the logging function, and record relevant information when an operation is completed.
+= (sender, e) => WriteLogToFile();
in conclusion
By using delegates and events, flexible callback mechanisms and publish-subscribe modes can be implemented, thereby improving code flexibility and decoupling. Delegates provide a type-safe way to pass methods as parameters, while events allow objects to notify other objects that something has happened. I hope this article can help you better understand and apply delegate and event technologies in C#. If you have any questions or need further information, please feel free to leave a message to discuss!
Hope this article about delegations and events in C# will help you. If you have any questions or need further information, feel free to let me know!
This is the article about delegation and events in C#: implementing a flexible callback mechanism. For more related C# delegation and event content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!