"C # series" You should know the delegates and events

Source: Internet
Author: User
Tags reflector

This article is more suitable for a certain development experience, a certain foundation, and the underlying code has a study of friends!!!

This article mainly uses the theory and the code example unifies the method to discuss the delegate and the event, involves some boundary technology, such as software architecture's OCP principle (open-closed principle),

Software architecture decoupling, design patterns (Sender-order) and event-driven models are difficult and deep, and are not suitable for beginners.

The first part of the Commission

About the contents of the consignment, mainly around to discuss.

What is a delegate (what)

(i) One of the contexts in which the Commission arises

1. Let's start by assuming that a scenario requires:

Design a system to meet the following conditions:

(1) At present, only the Chinese and the British use the system;

(2) Enter the user name and the corresponding language to the system, and the greeting in the corresponding language will be generated;

(3) Later, there may be other national languages to join the system (part of the system change);

2. Technical Solution Realization

With regard to the implementation of the technical scheme, we can adopt one of the three ways.

In order to better describe the mandate, we have implemented three technical solutions, and identified their relationship with each other.

2.1 General Implementation

Code (console program)

View Code

Result

Analysis

2.2 Implementation with interface

As above, we have analyzed the problem in solution one, in order to better solve the problem of the existence of the solution, we adopt the form of interface-oriented programming to achieve.

2.2.1 What is interface-oriented programming?

Interface-oriented programming is mainly to solve the "static and dynamic Problems" in the design of software architecture, that is, the package is constant (static), and the Peel change (pull change).

Code:

View Code

Result

Analysis:

(1) As above, we will change factor "language" stripping out, forming an interface, as long as each additional language, just realize the interface can, meet the OCP principle, basically solve the problem existing in the scheme one;

(2) The above code is only to demonstrate the function of interface-oriented programming, imperfect, interested readers, can be self-improvement (such as the definition of language as enumerated type, etc.);

Program two code, careful readers will find that the main method of new three objects, if the system has 300 languages later, it is not new 300 classes, so it is not conducive to code maintenance Ah, how to solve this problem? (hint that the problem can be solved by abstracting the factory in design mode)

2.3 Implementation with delegates

Here, do not contact the delegation of the reader, first skip this section, read down, after reading (iii) how the delegate (How to use), then look at this section.

Code

View Code

Result

2.3 Analysis of the relationship between the above three implementation scenarios

By appealing to three ways of comparison, it is easy to draw the following conclusions of the Commission:

(1) Abstract method, shielding method details, call just pass the method name can be;

(2) can realize the decoupling of the program, loose coupling (in scheme one, the Getgreetingcontens method body new Greettousers object, strong coupling)

(3) The delegate generally plays the role of the intermediary, this function is very obvious in the Commission event (the second part of the event will be discussed in detail)

If we rent a house, you can directly find the landlord (the general method of technical implementation, strong coupling, so that tenants and landlords directly contact), but also to find intermediaries (technical implementation of the Commission, loose coupling, tenants through the intermediary to contact the landlord)

2.4 Delegation Background Overview

The important background of the delegate is the event-driven model (about what is event and event-driven, discussed in the second part of this article).

(ii) Definition of delegation

Define the delegate with the Delegate keyword (note that the delegate is not a method body, similar to the method inside the interface), before defining the delegate, two questions must be clarified:

1. The method that the delegate will bind;

2. The parameter type of the delegate, the number of formal parameters and the return value of the delegate must match the parameter type, the number of parameters and the return value of the method to be bound;

(iii) Related concepts

The related concepts involved in delegation are function pointers, type security, events, lambda expressions, etc.

1. Function pointers: in C + +, a pointer to a category, the main point to the function (variable pointer, the main point to the variable address), you can interpret the C # delegate as a function pointer;

2. Type safety: in C + +, we all know that pointers are type unsafe (return values, return types, and when they are returned, which are unknown), whereas delegates are type-safe;

3. Event: An event can be understood as a special case of a delegate (in the second part of this article)

4.LAMBDA Expressions: Delegates are combined with LAMBD expressions for efficient programming, like jquery's "less code to do more", and the combination of delegates and lambda,linq, allowing shorter code to achieve more complex functions ( Lambda and lambda trees are not explained in this article and will be explained in subsequent articles)

(iv) Composition of the Commission

Broadly divided into two parts: declaring delegates and registering methods (also called binding methods)

1. Declaration of Delegation

declaration with delegate;

2. Binding method

Binding concrete method, passing the method name;

(v) Type of consignment

Delegate types, generally divided into multicast delegates and unicast delegates

1. Unicast delegation: How to bind an order

2. Binding Multiple methods

(vi) Entrusted operation

1. Binding method

2. Unbind method

What problems can be solved by two delegates (can do)

1. Avoid the existence of a large number of if....else in the core method .... Statement (or Swich switch statement);

2. Meet the OCP principle of program design;

3. Extensibility of the program;

4. Binding events;

5. Combine lambda expressions, simplify code, and efficiently program;

6. Realize the loose coupling (decoupling) of the program, which is more obvious in the event;

How do I use a delegate (how to uses) (this article does not talk about anonymous delegation, anonymous delegate specific content, will be explained in the Lambda chapter)

(i) Basic composition of the Commission

Typically, the steps to use a delegate are the same as the steps to use a class. Broadly divided into two steps: defining delegates and Binding methods (delivery methods)

1. Defining delegates

Define the delegate with the Delegate keyword (note that the delegate is not a method body, similar to the method inside the interface), before defining the delegate, two questions must be clarified:

(1). The method that the delegate will bind;

(2). The parameter type of the delegate, the number of formal parameters and the return value of the delegate must be the same as the parameter type, the number of parameters and the return value of the method to be bound;

Public delegate  delegate return type  delegate name (formal parameter)

Example: As above we entrust the greeting that will represent the system output

A. The method that the delegate will bind

public string Chinesepeople (string UserName)        {            string greetcontents = "Hello!" + UserName;            return greetcontents;        }        中文版 people public        string Englishpeople (string UserName)        {            string greetcontents = "Hello," + UserName + "!";            return greetcontents;        }        Non-Anglo-Chinese public        string otherpeople (string UserName)        {            return "Sorrry, the current system only supports Chinese and English";        }

B. As can be seen from the above method, the return type of the method is string, and the method has a string-type parameter, which is consistent when the delegate is defined

Defines the delegate public delegate string delegategetgreeting (string UserName);

2. Binding method

When you use a delegate, you pass the method name as a parameter to the delegate.

1 greettousers greettousers = new Greettousers (); 2 getgreetingcontents (UserName, Greettousers.chinesepeople)

(ii) Delegate binding method

1. How to bind an order

Bind order method, pass a single method name to delegate

View Code

Another less canonical notation: no getgreetingcontents (String username,delegategetgreeting delegategetgreeting) method

View Code

The reason why is not standardized, mainly in the project, is not conducive to the modularity of the code.

2. Bind multiple methods (multicast delegates)

Note: When you bind multiple methods, the delegate scope type must be of type void, otherwise only the value of the last binding is returned.

Binding multiple methods, using + = Binding

View Code

3. Unbind method

The method of unpacking the binding, using the-= Unbind

View Code

(iii) Commission mechanism

Use the following code through the Disassembly tool. NET Reflector Disassembly

View Code

Anti-assembly

Analysis:

1. Three core methods: Begininvoke,endinvoke and Invoke

(1) using Invoke to complete the marshaling of a delegate method is similar to using the SendMessage method to send a message to the interface thread, which is a synchronous method. This means that the Invoke method does not return until the method of the invoke Marshal is executed, and the caller thread is blocked.

(2 Marshals a delegate method using the BeginInvoke method, similar to communicating with PostMessage, which is an asynchronous method.) That is, the method returns immediately after marshaling, does not wait for the execution of the delegate method to end, and the caller thread will not be blocked. But the caller also

You can use the EndInvoke method or other similar WaitHandle mechanisms to wait for the completion of an asynchronous operation.

Summary: But in the internal realization, invoke and BeginInvoke all use the PostMessage method, thus avoids the problem which the SendMessage brings. The synchronous blocking of the Invoke method is done by the WaitHandle mechanism.

Tips:

Recently viewed an article, also said well: http://blog.csdn.net/goodshot/article/details/6157529

For a closer look, refer to CLR Via C #,

Part II Events

The event will be analyzed in the following four ways.

1. What is an event

2. What problems can be solved by the incident

3. How to use Events

4. Event mechanism

What is an event

When it comes to the Commission, the event is essentially a package of delegates, providing add_eventname (corresponding to + =) and remove_eventname (corresponding-=) access to the external, thus realizing the encapsulation of the class.

1. Type

Strongly-typed events and weakly-typed events

2. Some useful

(1) The WebForm control's Click event. A friend who has done webform development may be very familiar with events, such as dragging a button, double-clicking, and automatically generating a button's Click event in the background as shown in.

Principle: In a Windows application, the button class provides the Click event, which is essentially a delegate, and when we trigger the Click event, the handler method that is called requires a parameter whose arguments are defined by the delegate type.

(2) design mode publish/subscribe. Events are delegate-based and provide a publish/subscribe mechanism for delegates.

What problems can be solved by two events

1. Define the public delegate variable as a private variable to satisfy the encapsulation principle of the class;

2. Having the role of a delegate;

Three how to use events

1. Declaration of Delegation

public delegate void Delegategetgreeting (string UserName);

2. Declaring events

Just as with the delegate declaration, there is only one more keyword event

public event delegategetgreeting Eventgreet;

3. Time Registration method

The event registration method is the same as the delegate registration method.

1 Delegategreet dg= new Delegategreet (); 2//dg.delegategetgreeting = GTU. chinesepeople;//Registration Method 3 DG. eventgreet+= GTU. Chinesepeople;4 DG. Eventgreet + = GTU. Englishpeople;

4. Invoking events

Invoke the method that defines the event

Dg. GreetUser ("Xiao Wang");

The complete code is as follows:

View Code

Four-event mechanism

The essence of the event is the delegate, which provides two access methods add_EventName (corresponding to + =) and remove-eventname (corresponding-=), which we see through the. NET Reflector Disassembly tool.

Reference documents

"01" C # Advanced Programming (Seventh Edition) (Christian Nagel,bill Evjen and Jay Glynn authoring, Li Ming Translation, Huang revision)

"C # series" You should know the delegates and events

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.