Delegation

zhaozj2021-02-16  162

A function has a very common parameter, but a class with a method may feel strange, this is the characteristics of the entrusted. Many books say that the entrustment of the function pointer of C or C is not reasonable, because it allows the reference to the internal package method of the entrusted object, which is the parameters with a method, this method parameters have A certain rule, it can be static, or an instance method, the parameters of this method and the return type must be the same as the delegate object.

Entrusted like a middle agent, by reference to this delegate object, you can call the method referenced by this delegate object, that is, the method parameters it belongs. It can be called to call the method, without using which class of this method, because the method has been referenced by this delegate object, ie, we call this method to be implemented by this entrusted intermediate agent. One thing is that it is to delegate it is object-oriented, and type is safe. Look at the following code:

Class Principal {public string invokedMethod () // Note that this method returns String, the same object as the delegate, {Console.Writeline ("Hello");}}

Class class

{Principal classobj = new principal (); Delegate String is entered by the principal (); // Declare a return type for string delegate object is the principal Deleobj = New is entered by the principal (Classobj.invokedMethod); // Create a band Promotion object

DELEOBJ ();

}

Prustiglement is usually used in conjunction with an event. The event is the processing of user actions. When the user has some action, the event is executed by the delegate object, so the event is declared by delegate. The event can be used to use any type of delegation, but it is important to pay attention to follow the components to follow some rules: the delegate type of the event should have two parameters, one is the object source, one is an E-parameter. The object source represents the source of the event; e represents some information encapsulated, this e is derived from the Eventargs class. The event handler actually clicks on the event with the system defined by the system, but this time is defined by us. Examples of commission and events, reference http://blog.9cbs.net/jabby12/Archive/2004/08/02/58901.aspx

(Note: Many people say that it is difficult to understand the concept of entrusted, indeed the explanation on MSDN is not easy enough to understand, sound a bit abstraction, so I should try to stand in the user's perspective rather than the way. Concept of entrustment is clear)

转载请注明原文地址:https://www.9cbs.com/read-7963.html

New Post(0)