C # Delegate, custom, and event

Source: Internet
Author: User

Delegate:

In msdn, the first sentence about delegation is to associate the delegation with explicit or anonymous methods to instantiate the delegation. C ++ has a very powerful stuff-pointer. Of course, this is also a lot of criticism. C # has no pointer, but many times we need the powerful functions of C ++, but we cannot introduce memory defects in c ++, therefore, a delegate is displayed in C. "DelegateA keyword is used to declare a reference type. The reference type can be used to encapsulate naming or anonymous methods. The delegate is similar to the function pointer in C ++. However, the delegate type is safe and reliable. "(Msdn)

A delegate is a type of method that references the fee. The Mechanism is similar to class. Once we assign methods to the Delegate, the Delegate will have the same behavior as the method. The delegate method is similar to other methods in syntax.

Delegated features:

  • Pointer similar to C ++, but type-safe
  • Pass methods as parameters
  • Can be used to define callback Methods
  • Can be linked together, and multiple delegates can be called for an event
  • The method does not need to be exactly matched with the delegate, the covariant (return sub-type, as) and the inverter (incoming sub-type ).
  • Anonymous method. code blocks can be passed as parameters.

"Delegation is a type of secure encapsulation method, which is similar to function pointers in C and C ++. Unlike function pointers in C, delegation is object-oriented, type-safe, and insurance. The delegate type is defined by the delegate name. In this sentence, "delegation is object-oriented" requires additional attention. A delegate is essentially a class, so an instantiated delegate is an object that has all the features of an object.

The basic concept of delegation is pointer and object-oriented. After understanding these two points, the delegation will be basically mastered.

"The delegate type is derived from the delegate class in. NET Framework. The delegate type is sealed and cannot be derived from delegate or custom classes. Because the instantiation delegate is an object, it can be passed as a parameter or assigned to the attribute. In this way, a delegate can be accepted as a parameter and can be called later. This is called asynchronous callback. It is a common method used to notify the caller after a long process is completed. When using a delegate in this way, the code that uses the delegate does not need to know any information about the implementation of the method used. This function is similar to the encapsulation provided by the interface. "

If you understand the xuanjicang in the above sentence, or you can ask "when to use delegation and when to use interfaces", you have really understood delegation, you also have a deep understanding of interfaces (that is to say, you will not be entangled in the difference between abstract classes and interfaces. This problem is the most difficult problem for many new users to understand ). The answer to this question on msdn is briefly described below:

Delegation (encapsulation of a single method and multiple implementations) [determined by the design architecture model]

Interface (encapsulate a set of related methods, single implementation) [design architecture mode decision]

When the event design mode is used.

When static methods are encapsulated.

When the caller does not need to access other attributes, methods, or interfaces in the objects that implement the method.

A convenient combination.

When the class may require multiple implementations of this method.

When there is a set of methods that may be called.

When the class only needs a single implementation of the method.

When the class using the interface wants to forcibly convert the interface to another interface or class type.

When the implemented method is linked to the type or identifier of the class: for example, compare the method. (Special Case, need to understand)

As for the Use steps of delegation, I will not write it out. If not, go to msdn.

However, you need to add generic delegation, which is often used in practice.

Public Delegate string processdelegate <t, s> (T S1, s S2, Params s [] S3 );

Public String SS (string SS, int II, int [] III ){

Return NULL;

}

Public static void main (){

Asyncdemo SC = new asyncdemo ();

Processdelegate <string, int> Pd = new processdelegate <string, int> (SC. SS );

}

Event:

"When other classes or objects are concerned, classes or objects can be notified through events. The class for sending (or triggering) events is called "publisher", and the class for accepting (or processing) events is called "subscription ". "

The above sentence describes the most essential functions of an event, which is used for the upper layer of underlying notifications. The normal architecture design is a layered structure, and the layer structure is very important because the underlying layer is ignorant of the upper layer. At the beginning, this design was designed for decoupling and better object-oriented design, but the problem is how to solve the bottom-up information flow. For top-down calls, we can get everything done through the interface. The upper layer can see the service interfaces provided by the lower layer, so normal calls can be ensured all the way down, and the bottom layer can call the service interfaces provided by the middle layer, the implementation of the middle-level service interface calls the underlying service interface, which is a perfect design pattern. Each layer no longer depends on each other and hides implementation details. But now we have the simplest problem: how to implement it if the underlying layer is required to trigger upper-layer behaviors. Many programmers tell me this is simple, round-robin. The underlying layer keeps round-robin. If so, a thread is started to handle this matter. For this solution, you only need to open one more service interface at the underlying layer, which indicates what is happening now, and then check the interface regularly at the upper layer. If yes, take the corresponding action. Of course, this solution is also a solution, but it is estimated that you do not think it is good. First, it cannot be real-time. Because of polling, there must be a time difference problem, that is, the response time problem. In addition, separate polling threads consume space and time. The most depressing thing is that the consumption of time and space is irrelevant to the response time. In short, if you want a short response time, it means you have to waste a lot of time and space, and vice versa. Of course, this method also solves the problem of multi-thread conflicts, involving multi-thread conflicts and lock unlocking, so I don't think you are afraid of how powerful your logic capabilities are and how patient you are, as the scale of the project grows and the number of threads increases, it will be a matter of time before your brain crashes.

Here we introduce the event mode.

Let's take a look at the features of the event:

  • The publisher determines when an event is triggered, and the user determines the operation to be performed to respond to the event.
  • An event can have multiple subscribers. One subscriber can process multiple events from multiple publishers.
  • Events without subscribers will never be called
  • Events are usually used to notify users of operations.
  • If an event has multiple subscribers, multiple event handlers are synchronously called when the event is triggered.
  • Support asynchronous call
  • Event synchronization threads can be used
  • In the. NET Framework class library, events are based on the eventhandler delegate and eventargs base class.

C # The class library comes with a lot of events, especially those controls. For the underlying trigger upper layer problem that I mentioned, most of them need custom events. (I will not talk about the use of self-contained events in the library. If you won't, I'm sorry for the audience .) So here we will focus on the issue of custom events:

Events are messages sent from classes and objects to the outside world. The execution of events calls our prepared processing methods through event delegation. To respond to certain events and execute the methods we specify for certain events, perform the following steps:

  • Declaring delegation and events
  • Add an event trigger method, that is, the notification recipient method.
  • Add event triggering Method
  • Recipient localization RESPONSE METHOD
  • Subscribe to events by recipient

The most time used in Windows programming is the control time. Microsoft gives us a good way to focus on the design and encoding of the event execution method, however, if we really understand the true execution principles of events, the improvements to our programming are very good, for example, in Windows programming, if I click a button to trigger the button's Click Event button?click () {}, but sometimes we do not only want to trigger the button's click event, I also want to call other times for sequential execution. To implement this method, besides the call to other methods at the end of the method, you can also encapsulate other methods that require sequential execution into the delegate object of the Click Event of the button, so that the program in the destroyed method list can be executed sequentially, the implementation of this method is based on the premise of clear event triggering and delegate call.

Events are messages sent from classes and objects to the outside world. The execution of events calls our prepared processing methods through event delegation, but first responds to messages. To respond to certain events and execute our intended methods for certain events, follow these steps:

1. Declare event delegation.

2. Declare the event.

3. Add an event trigger method.

4. Add the event handler (the method for responding to the event ).

5. Bind the specified event handler to the event to be processed (subscribe to the event ).

6. Operate user information and trigger the event (call the trigger method of the event ).

7. Execute the event processing program we need through the callback of the event Delegate.

The following is an example of a simple custom event handler (console program)

Namespace event
{
// Event publishing Class
Public class testeventsource
{
// Define the event parameter class
Public class testeventargs: eventargs
{
Public readonly char keytoraiseevent;
Public testeventargs (char keytoraiseevent)
{
Keytoraiseevent = keytoraiseevent;
}
}

// Define delegate
Public Delegate void testeven thandler (Object sender, testeventargs E );
// Declare the event object with the event keyword
Public event testeven thandler testevent;

// Event trigger Method
Protected virtual void ontestevent (testeventargs E)
{
If (testevent! = NULL)
Testevent (this, e );
}

// Events
Public void raiseevent (char keytoraiseevent)
{
Testeventargs E = new testeventargs (keytoraiseevent );
Ontestevent (E );
}

}
// Event listening class
Public class testeventlistener
{
// Define the event processing method. It has the same parameter and return value type as the delegate of the declared event.
Public void keypressed (Object sender, testeventsource. testeventargs E)
{
Console. writeline ("Sender: {0}, calculated as: {1}", sender, E. keytoraiseevent );
}

// Subscribe to events
Public void subscribe (testeventsource evensource)
{
Evensource. testevent + = new testeventsource. testeven thandler (keypressed );
}
// Cancel the subscription event
Public void unsubscribe (testeventsource evensource)
{
Evensource. testevent-= new testeventsource. testeven thandler (keypressed );
}
}

// Test class
Public class test
{
Public static void main ()
{
// Create an event source object
Testeventsource es = new testeventsource ();
// Create a listener object
Testeventlistener El = new testeventlistener ();
// Subscribe to events
Console. writeline ("subscribe to events/N ");
El. subscribe (ES );
// Events
Console. writeline ("enter a character and press ENTER ");
String S = console. Readline ();
Es. raiseevent (S. tochararray () [0]);
// Cancel the subscription event
Console. writeline ("/n unsubscribe event/N ");
El. Unsubscribe (ES );

// Events
Console. writeline ("enter a character, and then press ENTER ");
S = console. Readline ();
Es. raiseevent (S. tochararray () [0]);

 

}
}

}

Program Execution completion

Subscribe to events

Enter a character and press Enter.
Aaaa
Sender: event. testeventsource, which is

Cancel subscription event

Enter a character, and then press ENTER

Testeventsource class. It is equivalent to a Windows control class. It is the event source, contains the event declaration, the event parameter class that stores the call parameters, and the event triggering method.

Testeventlistener class. He provides the event processing program and implements the bonding between the event processing program and the event object. Of course, the time processing program can be stored elsewhere and put together with the bonding program (subscribe to the event) for ease of understanding and calling.

Class test: instantiate the event source object of the Custom Event and call subscribe (es) in the testeventlistener class. The method is used to bond the event object and event handler (subscribe to the event ), call raiseevent (char keytoraiseevent) in the testeventsource class to raise an object and assign a callback to handle the event specified by the object. Complete the whole Custom Event.

Among them, raiseevent (char keytoraiseevent) is equivalent to the execution entry of custom events like main, start from this method ---> call event Delegate ----> Find the method set encapsulated by the event subscription event program ----> call the delegate callback event handler and pass the parameter ---> execute the event handler.

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.