SoFunction
Updated on 2025-04-12

Detailed analysis of commissions in C# and complete application summary

In C#,DelegateIs a type-safe function pointer that allows a program to pass a method as a parameter, or assign a method to a delegate instance. Delegation is a very powerful feature in C# programming. It has been widely used in various scenarios such as event processing, callbacks, asynchronous programming, etc. This article will introduce in detail the basic concepts, usage and advanced applications of C# delegation.

1. Basic concepts of delegation

1.1 Definition of Delegation

Delegates are types used to encapsulate methods with specific signatures. In C#, delegates allow you to pass or assign a reference to a variable as a parameter. The delegate-defined method signature includes the parameter type and return type of the method. The basic syntax of delegation is as follows:

public delegate Return type Entrust name(Parameter Type1 parameter1, Parameter Type2 parameter2, ...);
  • Return type: The return value type of the method.
  • Entrust name: The name of the delegate type.
  • Parameter type 1, Parameter type 2, ...: The parameter type accepted by the method.

Example:

public delegate int MathOperation(int a, int b);

A delegation is defined hereMathOperation, it can point to any accepting twointParameter and return aintMethod of type result.

1.2 Create a delegate instance

Once the delegate type is defined, a delegate instance can be created and pointed to a signature-compliant method. Here is an example of creating a delegate and calling a method:

public class Program
{
    public delegate int MathOperation(int a, int b);
    public static int Add(int a, int b)
    {
        return a + b;
    }
    public static int Subtract(int a, int b)
    {
        return a - b;
    }
    public static void Main()
    {
        // Create a delegate instance and point to the Add method        MathOperation operation = new MathOperation(Add);
        (operation(10, 5)); // Output 15        // Point the delegate to the Subtract method        operation = new MathOperation(Subtract);
        (operation(10, 5)); // Output 5    }
}

In this example,MathOperationis a delegate type that points to a method that accepts two integers and returns an integer. We implement method switching by creating delegated instances and assigning values ​​to different methods.

2. Multicast delegation

2.1 The concept of multicast delegation

A C# delegate can point to not only one method, but also multiple methods. This function is calledMulticast delegation. pass+=Operators, we can add multiple methods to a delegate instance, which will invoke these methods in the order in which they are added.

Example:

public delegate void Notify(string message);
public class Program
{
    public static void SendEmail(string message)
    {
        ("Sending Email: " + message);
    }
    public static void SendSMS(string message)
    {
        ("Sending SMS: " + message);
    }
    public static void Main()
    {
        Notify notify = new Notify(SendEmail);
        notify += SendSMS; // Add method        notify("Hello World!"); // Output: Sending Email and Sending SMS    }
}

In this example,NotifyDelegation points to two methods:SendEmailandSendSMS. When callednotifyWhen , the two methods will be called in turn.

2.2 Return value of multicast delegation

When a delegate points to multiple methods, if the return type of the delegate isvoid, then each method is called and no results are returned. However, if the return type is notvoid, then only the return value of the last method will be used as the return value of the delegate.

3. Type of delegation

3.1 Built-in delegate type

C# provides several commonly used built-in delegates that can be used more easily in common programming patterns:

  • Action: A method type without a return value, usually used to handle operations that do not require a return value.
  • Func: A method type with a return value, which can accept up to 16 input parameters.
  • Predicate: The method type that returns a Boolean value, usually used for conditional judgment.

Example:

// Action exampleAction<string> greet = name => ("Hello, " + name);
greet("Alice"); // Output "Hello, Alice"// Func exampleFunc<int, int, int> add = (a, b) => a + b;
(add(10, 5)); // Output 15// Predicate examplePredicate<int> isEven = num => num % 2 == 0;
(isEven(4)); // Output True

3.2 Delegated generic support

C# supports generic forms of delegates, making delegates more flexible and reusable. Generic delegates can accept any type of parameters and return types.

Example:

public delegate T MyGenericDelegate<T>(T value);

4. Anonymous methods and Lambda expressions

4.1 Anonymous method

Anonymous methods are a way of defining delegates. They do not need to specify the method name, but provide the method body directly when the delegate is instantiated.

Example:

MathOperation operation = delegate(int a, int b)
{
    return a + b;
};
(operation(10, 5)); // Output 15

4.2 Lambda Expressions

Lambda expressions are a more concise way to represent anonymous methods, using=>Symbols to separate parameters and method bodies. Lambda expressions make the code more concise and easy to read.

Example:

MathOperation operation = (a, b) =&gt; a + b;
(operation(10, 5)); // Output 15

5. Delegation and Events

5.1 The concept of events

Entrustment is closely related to the event. In C#eventDelegates are often defined. Events provide a mechanism that allows objects to notify other objects of their state changes. Events are usually declared by a delegate, allowing other objects (event subscribers) to register event handling methods.

Example:

public class Button
{
    public delegate void ClickEventHandler(object sender, EventArgs e);
    public event ClickEventHandler Click;
    public void OnClick()
    {
        Click?.Invoke(this, ); // Trigger event    }
}
public class Program
{
    public static void Main()
    {
        Button button = new Button();
         += (sender, e) =&gt; ("Button clicked!");
        (); // Output "Button clicked!"    }
}

In this example,ButtonThe class defines aClickEvent, it usesClickEventHandlerDelegate to encapsulate event handling methods. When the button is clicked,OnClickThe method triggers the event, and all methods that subscribe to the event will be executed.

6. Delegation and asynchronous programming

6.1 Asynchronous Delegation

Delegates can also be used for asynchronous programming. passBeginInvokeandEndInvokeMethods, delegates can call methods asynchronously without blocking the current thread. This is very useful when dealing with long-running tasks.

Example:

public delegate void LongRunningOperation();
public class Program
{
    public static void DoWork()
    {
        ("Starting work...");
        (2000);  // Simulate long-running operations        ("Work done.");
    }
    public static void Main()
    {
        LongRunningOperation operation = new LongRunningOperation(DoWork);
        // Asynchronous execution        IAsyncResult result = (null, null);
        ("Main method continues running while work is in progress.");
        (result);  // Wait for the asynchronous operation to complete    }
}

7. Pros and cons of delegation

advantage:

  • flexibility: Delegates provide a flexible way to call methods, which can pass method references as parameters, or assign values ​​to delegate instances.
  • Decoupling: Delegate decouples the caller of the method and the called method, improving the maintainability of the code.
  • Supports multicast and asynchronous: Delegation can point to multiple methods, support asynchronous calls, and is suitable for application scenarios such as event-driven and callback functions.

shortcoming:

  • Performance overhead: Delegation as object reference will introduce a certain performance overhead, especially in scenarios where frequent calls are performed.
  • Debugging complexity: Multicast delegates can make debugging complicated because delegates may point to multiple methods and the order of calls is uncontrollable.

Summarize

Delegates in C# are a powerful and flexible feature that allows programs to improve code flexibility and scalability through reference methods. Delegation is widely used in event processing, callbacks, asynchronous programming and other scenarios. Through built-in delegate types, anonymous methods, and Lambda expressions, C# delegates provide a variety of concise and efficient ways to organize your code. Understanding the basic usage and advanced features of delegation can help developers write clearer, flexible and efficient code.

This is the article about the detailed analysis and complete application summary of commissions in C#. For more related C#, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!