Delegate (C # Programming Guide)

Delegate is a reference type, reference to a method represents a particular parameter list and return type. In the instance of the delegate, you can be instances associated with any compatible method signature and return type. You can call the method through a delegate instance.

A method for transmitting delegate to other methods as parameters. Event handler method is through the delegate invocation. You can create a custom method, when a specific event occurs, a class (such as Windows controls) you can call your method. The following example demonstrates a proxy statement:

public delegate int PerformCalculation(int x, int y); 

The delegate can be assigned to any class or method of any accessible structure that matches the delegate type. The method may be a static method, a method may be instances. Such changes will be able to programmatically invoke the method can also insert new code to the existing class.

 Remark

In the context of method overloading, signature method does not include a return value. But in the context of the commission, the signature includes the return value. In other words, the method and the delegate must have the same return type.

The ability to reference method as a parameter makes it ideal for delegate defined callback method. For example, a reference to a method of comparing two objects may be transferred to the sorting algorithm as a parameter. Since the comparison code in a separate process, thus sorting algorithm can be written more common way.

Commissioned Overview

Entrusted with the following properties:

  • Principal C ++ like function pointers, but delegate fully object-oriented, C ++ like function pointers will remember, and a delegate instance encapsulates a method objects simultaneously.

  • The method allows to delegate passed as parameters.

  • Delegate can be used to define the callback methods.

  • Delegate can be linked together; for example, you can call multiple methods for an event.

  • The method does not have to exactly match the delegate type. For more information, see using variations of commission .

  • C # 2.0 version introduced anonymous methods concept, as a parameter for a code block (not separately defined method) is passed. C # 3.0 introduces Lambda expressions, they may be using more concise write inline code block. Anonymous methods and Lambda expressions (in certain contexts) can be compiled as a delegate type. These functions are now collectively known as anonymous functions. To learn more about lambda expressions, see  lambda expressions .

  • https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/delegates/

Guess you like

Origin www.cnblogs.com/deepalley/p/12173899.html