Those years that plague us (C #),

Source: Internet
Author: User

Those years that plague us (C #),

Entrusting this thing is not very easy to understand, but it is often used at work. You can see it everywhere. It makes people feel love and hate, I believe many people have been troubled by it.

When it comes to delegation, if you have learned C language, you will immediately think of function pointers.

What is delegation? The delegate is type-safe in C #. You can subscribe to one or more function pointers with the same signature method. The delegate can pass functions as parameters. The practical significance is to let others proxy your affairs. A delegate can be seen as a pointer to a function. An integer can point to it with an integer variable, and an object can point to it with an object variable,
A function can also point to it with a delegate variable. We can choose to regard the delegate type as an interface that defines only one method, while the delegate instance can be seen as an object that implements that interface.

The use of delegation must meet four conditions:

  • Declares the delegate type;
  • A method must contain the code to be executed;
  • You must create a delegated instance;
  • You must call the (invoke) delegate instance.
Delegated statement

How to declare delegation: delegate return value type delegate type name (parameter)

The delegate statement is basically the same as the interface method statement, but a delegate keyword is added before the return type keyword.

There are four types of delegation:

// 1. no parameter no return value public delegate void NoParaNoReturnEventHandler (); // 2. public delegate void WithParaNoReturnEventHandler (string name); // 3. no parameter returns public delegate string NoParaWithReturnEventHandler (); // 4. there are parameters that return values: public delegate string WithParaWithReturnEventHandler (string name );

If the code wants to execute the operation but does not know the operation details, you can use the delegate. For example, the Thread class knows what to run in a new Thread. The only reason is that it provides a ThreadStart or ParameterizedThreadStart delegate instance when starting a new Thread.

Thread th = new Thread(Test);th.Start();public Thread(ThreadStart start);public delegate void ThreadStart();

ThreadStart is a delegate with no parameters and no return values.

Static void Test () {Console. WriteLine ("Thread method ");}

The function signature of the Test method must be the same as the function signature that authorizes ThreadStart.

Delegated call

You must instantiate the delegate before calling it.

The function signature must be consistent with the delegate signature. NoParaNoReturnEventHandler _ NoParaNoReturnEventHandler = ConsoleInfo;, the compiler helps us with new, but it cannot be written as NoParaNoReturnEventHandler _ NoParaNoReturnEventHandler = leleinfo ();

This makes function calls.

# Region delegate call public static void Show () {// instantiate delegate NoParaNoReturnEventHandler _ NoParaNoReturnEventHandler = new delegate (ConsoleInfo); // delegate _ delegate = ConsoleInfo; // abbreviation // The delegate call is called through Invoke (), or _ NoParaNoReturnEventHandler can be omitted directly. invoke (); // _ NoParaNoReturnEventHandler ();} private static void ConsoleInfo () {Console. writeLine ("function call without parameters or return values");} # endregion

Why use delegate

We can call the method directly. Why do we still need to call the method through a delegate? What is the significance of delegation?

Disable modification and open extension. Logical separation.

You can regard the delegate as the parent class of the function, or a placeholder for a method.

Let's take a look at the code. Suppose there are two methods: one is English and the other is Chinese, and the function signatures of these two methods are the same.

Public static void SayChinese (string name) {Console. writeLine ("hello," + name);} public static void SayEnglish (string name) {Console. writeLine ("hello," + name );}

In this case,

MyDelegate. SayChinese ("James"); MyDelegate. SayEnglish ("zhangsan ");

If you want to call these two different methods, do you need to write different call codes?

Can we call only one method? The modification code is as follows:

Public static void Say (string name, WithParaNoReturnEventHandler handler) {handler (name);} public static void SayChinese (string name) {Console. writeLine ("hello," + name);} public static void SayEnglish (string name) {Console. writeLine ("hello," + name );}

In this way, only one method is used to Say the call.

How to call it? Three call methods are as follows:

WithParaNoReturnEventHandler _ WithParaNoReturnEventHandler = new WithParaNoReturnEventHandler (MyDelegate. sayChinese); MyDelegate. say ("James", _ WithParaNoReturnEventHandler); MyDelegate. say ("James", delegate (string name) {Console. writeLine ("hello," + name) ;}); // The anonymous method MyDelegate. say ("James", (name) => {Console. writeLine ("hello," + name) ;}); // lambda expression

The above Code uses several call methods which are constantly optimized with the upgrade of C. The first is the traditional call method existing in C #1.0, and the second is the anonymous method call method in C #2.0. The so-called anonymous method is a method without a name, it is best to use the anonymous method when the method is called only once. The lambda expression in C #3. In fact, generic delegation is also supported, while. NET 3.5 introduces a group of generic Delegate types named Func. It can obtain multiple parameters of the specified type and return another value of the specified type.

That is to say, the caller determines the specific method to be called, which gives more flexibility and scalability. Why do we say that if I want to speak English first and then Chinese again in some cases, how can we achieve this if I have not commissioned it? See the following code:

        public static void SayEnglishAndChinese(string name)        {            SayEnglish(name);            SayChinese(name);        }        public static void SayChineseAndEnglish(string name)        {            SayChinese(name);            SayEnglish(name);        }

What if I suddenly want to add a Russian? The code of the called party has to be modified again. Is it crazy if the code goes on like this? As new languages are added, the Code becomes increasingly complex and becomes increasingly difficult to maintain. Of course, you can use the design pattern to refactor the code without using the delegate, but it is very troublesome to implement it. You need to write more code...

The delegate can pass methods, and these methods can represent a series of operations. These operations are determined by the caller, so they are well extended and flexible. Instead of modifying existing methods, we only extend them as adding methods.

Some people may say that the same effect can be achieved when I call the method one by the caller?

But have you ever wondered whether you want to call a series of methods that you cannot reuse at all. The use of delegation is different. It is like a container of a method set. You can add or remove methods to it and reuse them. With delegation, you can delay the call of the method list and increase or decrease the list of methods at any time..The delegate encapsulates the method again.

Summary:That is, when you can only determine the function signature of the method and cannot determine the specific execution of the method, in order to achieve better extension, the new function is implemented in a form similar to the injection method, it can reflect the value of delegation.

The difference between delegate and direct function call:With delegation, you can point to any function, even if it is not defined before, instead of being limited.

Multicast Delegation

The delegate of a combination must be of the same type, which is equivalent to creating a new delegate object called in order of the combination. The combination of delegates is generally used for events, and is rarely used when common delegates are used.

Add the method to the delegate instance through +, and remove the method from the delegate instance.

+ And-are generated to simplify the Code. In fact, they call the Delegate. Combine method and Delegate. Remove method respectively.

If multiple methods with return values exist in the delegate, the return value of the call delegate is the return value of the last method.

Public static void MultipleShow () {// multicast delegate NoParaWithReturnEventHandler _ NoParaWithReturnEventHandler = new NoParaWithReturnEventHandler (GetDateTime); _ signature + = GetDateTime; Console. writeLine (_ NoParaWithReturnEventHandler ();} public static string GetDateTime () {return string. format ("Today is {0. ", DateTime. Now. Day. ToString ());}

Delegation summary:

  • The delegate encapsulates behaviors that contain special return types and a set of parameters, similar to interfaces that contain a single method;
  • The type signature described in the delegate type declaration determines which method can be used to create a delegate instance and the call signature;
  • In order to create a delegated instance, a method and (for instance methods) Call method are required;
  • The delegated instance is not easy to change, just like a String;
  • Each delegated instance contains a call list-an operation list;
  • The event is not a delegated instance-it is just a pair of add/remove methods (similar to the attribute value method/value assignment method ).

Common Use Cases: Form passing values, binding methods when the thread starts, and so on.

Example in life: Isn't everyone scrambling for a train ticket now? Using Cloud ticketing is equivalent to using a commission. You can buy a ticket on your own, or host the ticket on the cloud, when you are about to take a shot, you must refresh the page and place an order to lose the verification code. If you use cloud to grab a ticket, you only need to enter the ticket information in advance before placing the ticket, and you will no longer need to worry about it, automatic Ticketing, you do not need to know how cloud ticketing helps you achieve ticketing. A delegated instance can be created at the same time and number of trains. Many users use this delegated instance to snatch tickets.

Source code download: http://pan.baidu.com/s/1mic3QjQ

Related Article

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.