Delegate in C# is a type-safe function pointer used to encapsulate references to methods. Delegation allows you to pass methods as parameters to other methods, or store methods in variables for subsequent calls. This design pattern is particularly commonly used in scenarios such as event processing, callback functions, asynchronous programming, etc.
The following is a detailed explanation of the C# delegation and provides code examples.
1. Delegation definition
In C#, defining a delegate type requires specifying its parameter type and return type.
The syntax form is as follows:
public delegate Return type Entrust name(Parameter Type Parameter name[, ...]);
For example, define a delegate that takes two integer parameters and returns an integer:
public delegate int MathOperation(int num1, int num2);
2. Delegate instantiation
To use a delegate, you first need to create a delegate instance and assign a method with a matching signature to it.
Methods can be static, instance, or even anonymous methods or lambda expressions.
public static int Add(int a, int b) => a + b; public static int Subtract(int a, int b) => a - b; MathOperation addDelegate = new MathOperation(Add); MathOperation subtractDelegate = new MathOperation(Subtract);
Or use the implicit typed introduced in C# 2.0:
MathOperation addDelegate = Add; MathOperation subtractDelegate = Subtract;
3. Multicast Delegates
C# delegation can combine (+=) or separate (-=) other delegation instances to form a multicast delegation.
When called, the multicast delegate executes all associated methods in turn.
This is especially useful for scenarios such as event processing, where an event can have multiple subscribers (processors).
MathOperation combinedDelegate = addDelegate + subtractDelegate; int result = (10, 5); // Call firstAdd,Called afterwardSubtract
4. Use of the commission
Event handling
Events in C# are a special delegate type used to implement the publish-subscribe mode.
One class can publish events, and other classes can subscribe to these events and provide response methods.
When the event is triggered, all subscribers' methods are called in turn.
public class Publisher { public event EventHandler<MyEventArgs> CustomEvent; protected virtual void OnCustomEvent(MyEventArgs e) { CustomEvent?.Invoke(this, e); } public void TriggerEvent() { OnCustomEvent(new MyEventArgs("Event triggered")); } } public class Subscriber { public void Subscribe(Publisher publisher) { += OnCustomEvent; } private void OnCustomEvent(object sender, MyEventArgs e) { ($"Subscriber received event: {}"); } }
Callback function
Delegates can be used to encapsulate callback functions so that one method can accept another method as a parameter and be called when a specific time or condition is met.
public void PerformAsyncTask(Action<string> callback) { (() => { // Simulation time-consuming operation (1000); // Notify the result through callback after completing the task callback("Async task completed"); }); } // Use callbackPerformAsyncTask(result => { ($"Async task result: {result}"); });
LINQ query
In LINQ (Language Integrated Query), the delegation isFunc<T, TResult>
andAction<T>
It is widely used to define filtering, projection, aggregation and other operations.
var numbers = new[] { 1, 2, 3, 4, 5 }; // Use Func<int, bool> as predicate to filter even numbersvar evenNumbers = (n => n % 2 == 0); // Use Func<int, int, int> as comparator sortvar sortedNumbers = ((a, b) => (b));
5. Delegate and Lambda Expressions
C# 3.0 introduces lambda expressions, greatly simplifying the use of delegates.
Lambda expressions can create anonymous methods directly, which are ideal for short delegate definitions.
MathOperation addLambda = (int a, int b) => a + b;
6. Delegation and Anonymous Methods
C# 2.0 introduces anonymous methods that define delegate instances without creating separate named methods.
Although lambda expressions are more commonly used now, anonymous methods still have their value in some scenarios.
MathOperation addAnonymous = delegate(int a, int b) { return a + b; };
Summarize
As a result, C# delegation is a powerful language feature, which allows methods to be passed as parameters, and supports various programming modes such as event processing, callbacks, asynchronous programming.
By combining it with lambda expressions and anonymous methods, you can write delegate-related code more concisely and flexibly.
The above is personal experience. I hope you can give you a reference and I hope you can support me more.