In C #, event and delegate are two very important concepts. Because the use of events is very frequent in Windows applications, the implementation of events depends on delegate.
Here are some of the better information on the Internet on the collation of Delegage, as well as some of their own ideas.
What is delegate?
Delegate Chinese translation as "commissioned". The explanations for delegate in MSDN are as follows:
A delegate in C # is similar to a function pointer in C or C + +. Using delegates enables programmers to encapsulate method references within a delegate object. You can then pass the delegate object to code that can invoke the referenced method without having to know at compile time which method will be invoked. Unlike function pointers in C or C + +, delegates are object-oriented, type-safe, and secure.
Once a method is assigned to a delegate, the delegate has exactly the same behavior as the method. The use of a delegate method can have parameters and return values, like any other method, as shown in the following example:
public delegate void Del (String message);
Any method that matches the signature of the delegate (consisting of the return type and parameters) can be assigned to the delegate. This allows you to programmatically change the method invocation, and you can insert new code into an existing class. You can assign your own delegate method as long as you know the signature of the delegate.
Invoke delegate
When you construct a delegate object, you typically provide the name of the method that the delegate will wrap or use an anonymous method. When a delegate is instantiated, the delegate passes the method call to it to the method. The parameters that the caller passes to the delegate are passed to the method, and the return value from the method, if any, is returned to the caller by the delegate. This is referred to as invoking the delegate. You can call an instantiated delegate as the wrapped method itself. For example:
Create a method for a delegate.
public static void Delegatemethod (String message)
{
System.Console.WriteLine (message);
}
Instantiate the delegate.
Del handler = Delegatemethod;
Call the delegate.
Handler ("Hello World");
When a delegate is constructed as a wrapper instance method, the delegate references both the instance and the method. In addition to the methods it wraps, the delegate does not know the instance type, so the delegate can reference the object as long as it has a method that matches the delegate signature in any type of object. When a delegate is constructed to wrap a static method, it refers only to the method.
Callback
Because an instantiated delegate is an object, it can be passed as a parameter, or it can be assigned to an attribute. In this way, the method can accept a delegate as a parameter and can call the delegate at a later time. This is called an asynchronous callback, which is a common method used to notify callers after a long process completes. When a delegate is used in this way, the code that uses the delegate does not need to know any information about the implementation of the method being used. This feature is similar to the encapsulation provided by the interface.
Another common use of callbacks is to define a custom comparison method and pass the delegate to the sorting method. It allows the caller's code to become part of the sorting algorithm. The following example method uses the Del type as an argument:
public void Methodwithcallback (int param1, int param2, Del callback)
{
callback ("The number is:" + (param1 + PA RAM2). ToString ());
}
You can then pass the delegate created above to the method:
Methodwithcallback (1, 2, handler);
The following output is received in the console:
The number Is:3
Benefits of using delegates
Delegates allow class designers to detach type declarations and implementations.
When you use a delegate as an abstract concept, Methodwithcallback does not need to call the console directly-you don't have to consider the console when you design it. The role of Methodwithcallback is simply to prepare the string and pass the string to another method. This feature is particularly powerful because the delegate method can use any number of arguments.
The ability to refer to a method as a parameter makes the delegate an ideal choice for defining callback methods. For example, you can pass a reference to a sort algorithm to a method that compares two objects. Separating the comparison code makes it possible to write algorithms in a more general way.
How to use a delegate
1. Declaration of Commission
Declares a new delegate type. Each delegate type describes the number and type of parameters, and the return value type of the method that it can encapsulate. You must declare a new delegate type whenever you need a new set of parameter types or a new return value type.
2. Instantiation of the delegate
After you declare a delegate type, you must create the delegate object and associate it with a specific method. The signature of the method should be consistent with the signature defined by the delegate.
A delegate object can associate a static method or a Non-static method.
Once a delegate is created, its associated methods cannot be changed; The delegate object is immutable.
3. Invoke delegate
After a delegate object is created, the delegate object is typically passed to the other code that will invoke the delegate. The delegate object is invoked by the name of the delegate object (followed by the arguments to be passed to the delegate, enclosed in parentheses).
Here is an example:
Using System; public class Samplesdelegate {//declares a delegate for a, and returns a String. Public Deleg
Ate String mymethoddelegate (int myInt);
Defines some methods to which the delegate can point. public class Mysampleclass {//Defines a instance method. Public String mystringmethod (int myInt) {if (myInt > 0) re
Turn ("positive");
if (MyInt < 0) return ("negative");
Return ("zero");
}//defines a static method. public static String Mysignmethod (int myInt) {if (myInt > 0) return ("+"), if (MyInt < 0) return ("-"), Return ("")
; The public static void Main () {//creates one delegate to each. Mysampleclass MYSC = new Mysampleclass (); Mymetho
Ddelegate myD1 = new Mymethoddelegate (Mysc.mystringmethod);
Mymethoddelegate myD2 = new Mymethoddelegate (Mysampleclass.mysignmethod);
invokes the delegates. Console.WriteLine (' {0} is {1};
Use the sign/"{2}/". ", 5, MyD1 (5), myD2 (5)); Console.WriteLine (' {0} is {1}; Use the sign/"{2}/". ",-3, MyD1 ( -3), MyD2 (-3)); Console.WriteLine (' {0} is {1};
Use the sign/"{2}/". ", 0, myD1 (0), myD2 (0)); }/* This code produces the following output:5 is positive;
Use the sign "+". -3 is negative;
Use the sign "-". 0 is zero;
Use the sign "". */
Multi-channel broadcasting
When a delegate is invoked, it can call multiple methods. This is called multicast. To add an extra method to the delegate's method list (invocation list), simply add two delegates by using the addition operator or the addition assignment operator ("+" or "+ ="). For example:
Methodclass obj = new Methodclass ();
Del D1 = obj. METHOD1;
Del d2 = obj. METHOD2;
Del d3 = Delegatemethod;
Both types of assignment are valid.
Del allmethodsdelegate = d1 + d2;
Allmethodsdelegate + = D3;
At this point, Allmethodsdelegate contains three methods in its invocation list-Method1, METHOD2, and Delegatemethod. The original three delegates D1, D2 and D3 remain unchanged. When Allmethodsdelegate is invoked, all of these three methods are called sequentially. If the delegate uses a reference parameter, the reference is passed to each of the three methods in turn, and the changes caused by one method are visible to the next method. If either method throws an exception, and the exception is not caught within the method, the exception is passed to the caller of the delegate and no longer calls the method later in the invocation list. If the delegate has a return value and/or an output parameter, it returns the return value and parameters of the method that was last called. To remove a method from the invocation list, use the subtraction operator or the subtraction assignment operator ("-" or "="). For example:
Remove Method1
allmethodsdelegate-= D1;
Copy allmethodsdelegate while removing d2
Del onemethoddelegate = allmethodsdelegate-d2;
Multicast delegates are widely used in event handling. The event source object sends event notifications to the recipient object that is registered to receive the event. To register an event, the receiver creates a method that is intended to handle the event, and then creates a delegate for the method and passes the delegate to the event source. When an event occurs, the source invokes the delegate. The delegate then invokes the event-handling method of the receiver and transmits the event data. The delegate type for a given event is defined by the event source.
This example shows how to combine multicast delegates. One use of delegate objects is that you can use the + operator to assign them to a delegate instance that you want to be a multicast delegate. A combined delegate can invoke the two delegates that make up it. Only delegates of the same type can be grouped.
Operator can be used to remove a component delegate from a grouped delegate.
delegate void Del (string s);
Class TestClass
{
static void Hello (string s)
{
System.Console.WriteLine ("Hello, {0}!", s);
}
static void Goodbye (string s)
{
System.Console.WriteLine ("Goodbye, {0}!", s);
}
static void Main ()
{
Del A, B, C, D;
Create the delegate object A that references
//The method Hello:
a = hello;
Create The delegate object B that references
//The method Goodbye:
b = Goodbye;
The two delegates, A and B, are composed to form C:
C = a + B;
Remove A from the composed delegate, leaving D,
//which calls only of the method Goodbye:
d = c-a;
System.Console.WriteLine ("Invoking delegate A:");
A ("a");
System.Console.WriteLine ("Invoking delegate B:");
B ("B");
System.Console.WriteLine ("Invoking delegate C:");
C ("C");
System.Console.WriteLine ("Invoking delegate D:");
D ("D");
}
Summary of Delegate
Delegate is a type in C # that is actually a class that holds a reference to a method. Unlike other classes, the delegate class can have a signature (signature), and it can only hold a reference to the method that matches its signature. The functionality it implements is very similar to the function pointers in C + +. It allows you to pass a method M of Class A to the object of another class B, so that the object of Class B can call this method M. However, compared with function pointers, delegate has many advantages that are not available in function pointers. First, a function pointer can only point to a static function, while delegate can refer to static functions and non-static member functions. When referencing a non-static member function, delegate not only holds a reference to this function's entry pointer, but also holds a reference to the class instance that called the function. Secondly, compared with function pointers, delegate is an object-oriented, type-safe, and reliable controlled (managed) object. That is, runtime can ensure that delegate points to an effective method, and you need not worry that delegate will point to an invalid address or a cross-border address.
His own understanding of Delegate
"Delegate is a type in C #. "Delegate is similar to class, class defines a type, and delegate also defines a type." Class can define a variety of classes, such as ClassA, CLASSB, and delegate can define a variety of proxies, such as Delegate1,delegate2. Unlike class, the definition of delegate has no fields, attributes, methods, etc., only signatures (return values and parameters).
"It's actually a class that can hold a reference to a method." The delegate object can hold a reference to a method that must be signed in the same way as the proxy type (this is the "delegate" interface that defines the callback method). The proxy object holds a reference to this method, and the invocation of the method is implemented when the proxy object is invoked. The invocation of a method can be achieved by invoking the proxy object because the address of the incoming method is assigned to the proxy object when the proxy object is instantiated, so that when the proxy object is invoked, the instruction pointer in memory points to the entry of the incoming method, executing the method body of the incoming method.
When using a proxy to implement multicast, a reference to multiple methods (that is, memory addresses) is saved to the proxy's method reference queue. When a proxy object is invoked, a queue is referenced according to the method of the proxy object, and the instruction pointer in memory points to the entry of each method, sequentially executing the method body of each method.
The publication and subscription of the event. An event is a class or object in which a class or object notifies the person of the matter through an event when a particular thing occurs. The class that sends (or raises) an event is called the publisher, and the class that receives (or handles) the event is called a Subscriber. The implementation of the event is dependent on the agent. The implementation of an event means that the Subscriber passes the method of responding to the event to the publisher, and the Publisher is able to invoke the method of responding to the event when certain events occur. In code-level implementations, the Publisher defines a delegate type, provides a public delegate object as a field or property, and a Subscriber (can be multiple) instantiates a delegate object by passing the method of responding to the event to the delegate type, and by + = operator to assign a delegate object to the Publisher's delegate object, which is actually multicast. When a particular event occurs, the publisher invokes the delegate object, the method that invokes the response event of all subscribers.
The above is a small set for you to introduce the in-depth understanding of C # in the delegate, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!