What does this delegate method do?

I read the MSDN page on delegates and they seem simple. Then I looked at some code that uses them, and I saw this:

public delegate void NoArguments(); public NoArguments Refresh = null; Refresh = new NoArguments( Reset ); 

This is the third line that bothers me. How can you delegate new ? This is not an object, this is a method, or rather, a delegate to a method. According to the example on the MSDN page, creating a delegate instance is done through a simple assignment, not a allocaiton. Also, why is new for the delegate taking the parameter Reset when the delegate declaration does not accept any parameters?

+6
source share
3 answers

A delegate is a "delegate method", but also an object. If you look at NoArguments in any decompiler, you will see that this is actually a class that inherits from MulticastDelegate , with several methods ( Invoke , BeginInvoke , EndInvoke ).

For historical reasons, C # allows you to instantiate this class using new NoArguments(method) . However, in modern versions, it also supports the shortcut method , which does the same. In both cases, you actually have an object of type NoArguments in Refresh .

+1
source

The delegate keyword indicates that the following is essentially the signature of the function, so Refresh becomes kind of like a pointer to a function that takes no arguments. However, in order to assign something to the Refresh pointer, you must tell it the function that it points to. In this case, this is the Reset function. In addition, the Reset function should not accept any arguments.

In addition, the syntax is:

 Refresh = Reset; 

also valid and is just syntactic sugar for a more formal syntax:

 Refresh = new NoArguments(Reset); 

in both cases, you can execute the Reset function by calling Refresh:

 Refresh(); 

Note, however, that if you execute Refresh() without assigning it, you can throw an exception. To prevent this, you need to check it for null:

 if (Refresh != null) Refresh(); else { // Refresh was never assigned } 
+4
source

You might think that a delegate is similar to a function type:

  • To declare a type, the function returns void and has no arguments:

     public delegate void NoArguments(); 
  • Declare a variable of the given type and initialize it:

     public NoArguments Refresh = null; 
  • Assign a new object to your variable. The object is actually a Reset function, which must have the same signature as your delegate:

     Refresh = new NoArguments( Reset ); 

UPDATE:

You can view the following link for more details: C # delegates

+2
source

Source: https://habr.com/ru/post/948992/


All Articles