Delegate (CLI)

from Wikipedia, the free encyclopedia

A delegate is a form of type safety function pointer used by the common language infrastructure (CLI). Delegates specify a method for calling and optionally an object for calling the method. Delegates are used, among other things, to implement callbacks and event listeners . A delegate object encapsulates a reference to a method. The delegate object can then be passed to a piece of code that can call the referenced method without having to know which method is called at compile time.

A multicast delegate is a delegate that references multiple methods. Multicast delegation is a mechanism that provides functionality to perform more than one method. There is a list of delegates that are maintained internally. If the multicast delegate is now called, this list of delegates is executed.

A common use of delegates in C # is to implement callbacks in event-driven programming. For example, a delegate can be used to indicate which method should be called when the user clicks a button. Delegates allow the programmer to notify several methods of an event occurring.

C # code example

The code below declares a delegatetype, that is SendMessageDelegate, takes one as a parameter Messageand returns one void:

delegate void SendMessageDelegate(Message message);

Code to define a method that takes an instantiated delegate as an argument:

void SendMessage(SendMessageDelegate sendMessageDelegateReference)
{
  // Rufe das Delegate und jedes andere verbundene Delegate synchron auf
  sendMessageDelegateReference(new Message("hello this is a sample message"));
}

The implemented method that will be executed when the delegate is called:

void HandleSendMessage(Message message)
{
  // Die Implementation für die Sender- und die Message-Klasse sind in diesem Beispiel irrelevant
  Sender.Send(message);
}

Code to call the SendMessageDelegatemethod, passing an instantiated delegate as an argument:

SendMessage(new SendMessageDelegate(HandleSendMessage));

Delegates (C #)

delegate void Notifier(string sender);  // Normale Signatur mit dem Schlüsselwort delegate

Notifier greetMe;                       // Delegate-Variable

void HowAreYou(string sender) {
  Console.WriteLine("How are you, " + sender + '?');
}

greetMe = new Notifier(HowAreYou);

A delegate variable calls the associated method and is called itself as follows:

greetMe("Anton");                       // Ruft HowAreYou("Anton") auf und druckt "How are you, Anton?" aus

Delegate variables are first-class objects of the form new DelegateType(obj.Method)and can be assigned to any suitable method or value null. You save a method and its receiver without parameters:

new DelegateType(funnyObj.HowAreYou);

The object funnyObjcan thisbe and be omitted. If the method staticis, it shouldn't be the object (also called an instance in other languages), but the class itself. It shouldn't abstractbe, but could new, overrideor virtuel.

To invoke a method successful with a delegate that has the method signature of the DelegateTypesame type with the same number of parameters ( ref, out, value), and the same type (including return type), respectively.

Multicast Delegates (C #)

A delegate variable can contain several values ​​at the same time:

void HowAreYou(string sender) {
  Console.WriteLine("How are you, " + sender + '?');
}

void HowAreYouToday(string sender) {
  Console.WriteLine("How are you today, " + sender + '?');
}

Notifier greetMe;

greetMe = HowAreYou;
greetMe += HowAreYouToday;

greetMe("Leonardo");                  // "How are you, Leonardo?"
                                      // "How are you today, Leonardo?"
greetMe -= HowAreYou;

greetMe("Pereira");                   // "How are you today, Pereira?"

If the multicast delegate is a function or has no parameter out, the parameter of the last call is returned.

Technical details

Although internal implementations may vary, delegate instances can be thought of as a tuple of an object and a method pointer and a reference (possibly null) to another delegate. Therefore, a reference to one delegate may be an indication of multiple delegates. When the first delegate is finished, when its chain reference is not null, the next is called, and so on until the list is complete. This pattern allows an event to have overhead scaling slightly from that of a single reference to being sent to a list of delegates, and is widely used in the CLI.

power

Delegates' performance was much slower than calling a virtual or interface method (1/6 to 1/8 times as fast in Microsoft 2003 benchmarks), but since the .NET 2.0 CLR in 2005, it's about as fast as interface Calls. This means that there is a small additional overhead compared to direct method calls.

There are very strict rules for building delegated classes.

See also

Web links

Individual evidence

  1. How to: Combine Delegates (Multicast Delegates) (C # Programming Guide). msdn.microsoft.com, accessed May 20, 2008 .
  2. About Microsoft's “Delegates” . Sun Microsystems. Archived from the original on February 10, 1999.
  3. ^ Wikibooks: C Sharp Programming / Delegates and Events .
  4. Hanspeter Mössenböck: Advanced C #: Variable Number of Parameters . Institute for System Software, Johannes Kepler University Linz, Department of Computer Science. Pp. 23-24. March 25, 2002. Retrieved August 4, 2011.
  5. Hanspeter Mössenböck: Advanced C #: Variable Number of Parameters . Institute for System Software, Johannes Kepler University Linz, Department of Computer Science. March 25, 2002. Retrieved August 4, 2011.
  6. ^ Jan Gray: Writing Faster Managed Code: Know What Things Cost . Microsoft. June 2003. Retrieved September 9, 2007.
  7. Oliver Sturm: Delegate calls vastly sped up in .NET 2 . September 1, 2005. Retrieved September 9, 2007.