Net 4.0 delegate delegate use details

  • 2020-06-07 04:21:42
  • OfStack

The delegate in.Net is functionally similar to the c language or the method pointer in c++, and can be invoked to complete a function or to return a result of a certain kind as if it were called method 1. Net, after all, is a higher level language, so is delegate Delegate, which is a data interface that contains Pointers to calling targets and methods. The delegates defined in.Net are inherited from MulticastDelegate, the multicast delegate, which is a delegate that can contain multiple calling methods.
1. Let's start with the definition of a delegate:
The C# code defines the delegate as follows
public delegate void DoSomething(int times);
The definition of a delegate consists of five parts
1) public represents the accessibility of the delegate
2) The delegate keyword means that 1 delegate is to be defined
3) void represents the return value of the delegate definition method
4) DoSomething is the name of the delegate
5) (int times) is the parameter list of the delegate method. The parameter list here can include ref parameter, out parameter, or parms variable number parameter. Note that if there are multiple invocation methods in the delegate, using the out parameter only returns the calculated value of the last successful execution of the delegate method
Defining a delegate in C# is very simple, just one more delegate keyword than before the return value of the method definition.
But we know that all user-defined delegates inherit from MulticastDelegate; MulticastDelegate is one class; So the custom delegate must also be a class; Take a look at the IL code above to prove our inference:

.class public auto ansi sealed delegates.DoSomething
    extends [mscorlib]System.MulticastDelegate
{
    // Methods
    .method public hidebysig specialname rtspecialname
        instance void .ctor (
            object 'object',
            native int 'method'
        ) runtime managed
    {
    } // end of method DoSomething::.ctor

    .method public hidebysig newslot virtual
        instance void Invoke (
            int32 times
        ) runtime managed
    {

    } // end of method DoSomething::Invoke

 
    .method public hidebysig newslot virtual
        instance class [mscorlib]System.IAsyncResult BeginInvoke (
            int32 times,
            class [mscorlib]System.AsyncCallback callback,
            object 'object'
        ) runtime managed
    {

    } // end of method DoSomething::BeginInvoke

 
    .method public hidebysig newslot virtual
        instance void EndInvoke (
            class [mscorlib]System.IAsyncResult result
        ) runtime managed
    {

    } // end of method DoSomething::EndInvoke

} // end of class delegates.DoSomething

2. A delegate is defined, of course, to use it, so here's how to use a delegate:
There are three types of delegates in.Net: methods, anonymous methods, and lambda expressions; Let's look at how the delegate is used in the form of a method definition

using System;

namespace delegates
{
 public delegate void DoSomething(int times);

    class Program
    {
        static void Main(string[] args)
        {
            // Declare the delegate variable and assign a value to it 
            DoSomething @do = DoA;
            // You can use + Number or += Add methods to the delegate 
            @do += DoB;
            // The methods in the delegate are executed in the order in which the delegate was added 
            @do(1);
            // You can also go through - Number or -=  Removes methods from the delegate 
            @do -= DoA;
            @do(2);

            @do -= DoB;
            // After you get rid of all the methods in the delegate, you can still call the delegate, just do nothing, right 
            @do(3);

            Console.Read();
        }
       // define 1 Five methods that delegate the same parameters and return values 
        static void DoA(int times)
        {
            Console.WriteLine("Do A {0}", times);
        }

 
        // define 1 Five methods that delegate the same parameters and return values 
        static void DoB(int times)
        {
            Console.WriteLine("Do B {0}", times);
        }
    }
}

The Main method in the above code first defines the delegate DoSomething variable @do and assigns the DoA method directly to the delegate variable. Then we add another method to this delegate using either the += symbol or the + sign; You can also use - or -= to remove the method from the delegate.
Delegates are more powerful than C/C++ method Pointers in that they can hold multiple methods and also perform +/- operations to add or remove methods from the list of methods.
There are several issues that need our attention when performing the delegate addition and subtraction operation:
1. How to write the statement of delegation
The delegate declaration can be written as follows

DoSomething @do = DoA;

This is actually a short way of writing it, and we know that in.Net 1.x this is not allowed until.Net 2.0, it has to be written in.Net 1.x

DoSomething @do = new DoSomething(DoA);

We want to add DoA plus DoB to @do at the time of the declaration

DoSomething @do = DoA + DoB;

You can't write it this way, the compiler doesn't work; Net 1.x must be used

DoSomething @do = new DoSomething(DoA) + new DoSomething(DoB);

2. What happens when you subtract from the delegate the way the delegate does not exist?
See the following code:

DoSomething @do = DoA;
@do -= DoB;

Line 1 I live @do and give DoA to it; Line 2 I tried to subtract DoB from @do. DoB does not exist in the @do method list. What happens? First of all, the compiler did not report an error, the program can compile normally; The program can execute normally when the execution code is found. When the @do delegate is called, the DoA method is executed correctly. This illustrates that.Net contains the error that we programmers made when we subtracted a method from the delegate variable that was not included in the delegate, and the error was not reported and performed normally.
3. Subtract the delegate, and all the delegates are gone. What happens? Look at the following code

DoSomething @do = new DoSomething(DoA) + new DoSomething(DoB);
@do -= DoA;
@do -= DoB;
@do(1);

Such code compiles successfully, but is reported at runtime as NullReferenceException; This is obviously not what we want, so you have to be careful when you subtract from the delegate.

<span style="text-decoration: line-through;">public delegate void DoIt(string task);

class Test
{
    static void Main(string[] args)
    {
        //DoIt Declare, endow 1 The method with a wider parameter is legal 
        DoIt doIt = new DoIt(DoItImpl);
        doIt("hello");
    }

    // Broader than the parameters in the delegate definition, string The type can be implicitly converted to object
    static void DoItImpl(object task)
    {
        Console.WriteLine("DoItImpl {0}",task);
    }
}
</span>


Related articles: