C # Delegate

Source: Internet
Author: User

Delegate is a type in C #. It is actually a class that can hold a reference to a method.
Unlike other classes, the delegate class can have a signature and can only hold references to methods that match its signature.

A delegate Declaration defines a reference type that can be used to encapsulate a method with a specific signature. A delegate instance encapsulates a static or an instance method. delegates are roughly similar to function pointers in C ++; however, delegates
Are type-safe and secure.

The above definition explains that a delegate Declaration defines a reference type, which is used to compress a method in a specified form. A delegate instance compresses a static or instance method. Delegates and function pointers in C ++ are similar. However, the difference is that delegate is safe and type-safe.

Found on the codeproject website.


C # delegate is a callback function. In other words, delegate is a way to provide feedback from Class-server to class-client.


C #'s delegate is a callback function. In other words, delegate is a way to provide feedback from the class server to the class client.

C # delegate is smarter then "standard" Callback because it allows defining a strict list of parameters which are passed from Class-server to class-Client


However, C # delegate is smarter than general callback functions. Because it allows defining a strict parameter list. The parameter list contains the parameters passed from the class server to the class client.

C #'s delegate type
Delegate is a function pointer, but compared with common function pointers, there are three main differences:

1) A delegate object can carry multiple methods at a time, instead of one at a time. When we call a delegate carrying multiple methods, all methods are called in order of the order in which they are loaded with delegate objects. Let's take a look at how to do this.

2) The method (methods) carried by a delegate object does not need to belong to the same category. All methods (methods) carried by a delegate object must have the same prototype and form. However, these methods can be either static or non-static and can be composed of one or more members of different categories.

3) A delegate type statement creates a new subtype instance, which is derived from. net Library Framework abstract base classes delegate or multicastdelegate, they provide a set of public methods for querying the delegate object or its carrying method (methods)
---
Its functions are very similar to function pointers in C/C ++.
It allows you to pass the method M of Class A to the object of Class B, so that the object of Class B can call this method M.
But compared with function pointers, delegate has many advantages that function pointers do not possess.

First, the function pointer can only point to static functions, while delegate can reference both static functions and non-static member functions.
When referencing a non-static member function, delegate not only saves the reference to this function entry pointer, but also saves the reference to the class instance that calls this function.

Second, compared with function pointers, delegate is an object-oriented, secure, and reliable managed object.
That is to say, the runtime can ensure that the delegate points to a valid method. You do not need to worry that the delegate will point to an invalid or out-of-bounds address.

It is easy to implement a delegate. You can use the following three steps to implement a delegate:

1. Declare a delegate object. It should have the same parameter and return value type as the method you want to pass.
2. Create a delegate object and pass in the functions you want to pass as parameters.
3. Use the object created in the previous step to call the method where an asynchronous call is to be implemented.

Using system;

Public class mydelegatetest
{
// Step 1: declare the delegate object
Public Delegate void mydelegate (string name );

// This is the method we want to pass. It has the same parameter and return value type as mydelegate.
Public static void mydelegatefunc (string name)
{

Console. writeline ("hello,", name );

}
Public static void main ()
{
// Step 2: Create a delegate object
Mydelegate
MD = new mydelegate (mydelegatetest. mydelegatefunc );
// Step 3: Call delegate

MD ("sam1111 ");

}
}

Output result: Hello, sam1111


After learning about delegate, let's take a look at how events are handled in C.

In C #, event processing is actually a delegate with a special signature, as shown below:

Public Delegate void myeventhandler (Object sender, myeventargs E );

The two parameters, sender represents the event sender, and E is the event parameter class. The myeventargs class is used to contain event-related data. All event parameter classes must be derived from the system. eventargs class. Of course, if your event does not contain parameters, you can directly use the system. eventargs class as the parameter.

With the implementation of Delegate, We can summarize the implementation of custom events into the following steps:

1. Define the delegate object type. It has two parameters. The first parameter is the event sender object, and the second parameter is the event parameter class object.
2. Define the event parameter class, which should be derived from the system. eventargs class. This step can be omitted if the event does not contain parameters.
3. Define the event processing method. It should have the same parameter and return value type as the delegate object.
4. Define the event object with the event keyword. It is also a delegate object.
5. Add the event to the event queue with the + = Operator (the-= operator can delete the event from the queue ).
6. Call the delegate method to write the event trigger method where an event needs to be triggered. In general, this method should be a protected access restriction. It cannot be called in public mode, but can be inherited by the quilt class. The name is oneventname.
7. Call the event trigger method to trigger the event where appropriate.

The following is a simple example:


Using system;
Public class eventtest
{
// Step 1, define the delegate object
Public Delegate void myeventhandler (Object sender,
System. eventargs E );
// Skip step 2
Public class myeventcls
{
// Step 3: Define the event processing method. It has the same parameters and return value type as the delegate object. //
Public void myeventfunc (Object sender,
System. eventargs E)
{

Console. writeline ("My event is OK! ");

}

}
// Step 4: Use the event keyword to define the event object
Private event myeventhandler
Myevent;
Private myeventcls
Myecls;
Public eventtest ()
{

Myecls = new myeventcls ();
// Step 5: add the event to the queue with the + = Operator
This. myevent + = new myeventhandler (myecls. myeventfunc );

}
// Step 6: Write the event trigger function by calling delegate
Protected void onmyevent (system. eventargs
E)
{
If (myevent! = NULL)

Myevent (this, e );

}
Public void raiseevent ()
{

Eventargs E = new eventargs ();
// Step 7: trigger the event

Onmyevent (E );

}
Public static void main ()
{

Eventtest ET = new eventtest ();

Console. Write ("Please input ''a '':");
String S = console. Readline ();
If (S = "")
{

Et. raiseevent ();

}
Else
{

Console. writeline ("error ");

}

}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.