Delegate to anonymous method to lambda expression, lambda expression

Source: Internet
Author: User

Delegate to anonymous method to lambda expression, lambda expression

What is Delegation

In a typical example, when the whole of a method is relatively fixed and a small part has changed, sometimes our common practice is: upload a variable to the method. The method determines the specific execution of these changes based on the parameter value. The whole example is as follows:

Using System; namespace DemoDelegate {class Program {static void Main (string [] args) {string input = Console. readLine (); string result = HandleString (input, "trim"); Console. writeLine ("I can achieve the same purpose without delegation. Result = "+ result) ;}/// <summary> /// append the time before the input content, perform corresponding processing. // </summary> /// <param name = "ActoinType"> </param> /// <returns> </returns> private static string HandleString (string input, string ActoinType) {switch (ActoinType) {case "trim": input = input. trim (); break; case "toLowerCase": input = input. toLower (); break; case "toUpperCase": input = input. toUpper (); break; default: break;} input = DateTime. now. toString ("yyyy-MM-dd HH: mm: ss ffffff") + input; // This is the fixed operation return input ;}}}

Ps: there are deficiencies in the above Code. After reading the code, you may wonder: why not process the changes that will be processed first in main and then call them. The answer is: when the HandleString method is complex enough and the context is closely linked, this method is required.

According to the idea of object-oriented encapsulation, this obviously does not meet the requirements of extended and open. At this time, I naturally wondered if I could pass the changed part in the form of a method? Lamp! Delegate appears

Idea: What type of method does HandleString receive this change? It is certainly not to write a method call in the parameter, because it is equivalent to giving the processing result to HandleString. It should be a new data type: a custom type. So let's look at the silly question: how do we define a class:

    class CatInfo    {        public int ID { get; set; }        public string Name { get; set; }    }

Class itself is a keyword, so we use delegate to define the type of a method class.

        public delegate string WhatToDo(string input);

In this case, delete is intended to be the class keyword. This class is not defined as a class, and has attributes, fields, and methods. It only defines a type of method. For example, this type of method must return a string, and a string is input in the method signature. This method for defining a class of methods is called delegation.

Let's take a look at the silly question, how do we instantiate a class.

            CatInfo info = new CatInfo();

Similarly, we instantiate a delegate.

Public static string Method1 (string input) {string result = "I am a normal method and return string. The input parameter is also a string, and my input value is: "+ input; Console. WriteLine (result); return result;} WhatToDo export nceofwhattodo = Method1;

Yes, there is no new Keyword, type instance = specific value (that is, int a = 1) can be, a careful understanding, it is nothing more than a method type (delegate ), assign a value to a method. At this time, it is not difficult to understand a complete chestnut:

Using System; namespace DemoDelegate {class Program {public delegate string WhatToDo (string input); static void Main (string [] args) {WhatToDo define nceofwhattodo = DoTrim; string input = Console. readLine (); string result = HandleString (input, instrnceOfWhatToDo); Console. writeLine ("I will have the same output result. Result = "+ result);} public static string DoTrim (string input) {string result = input. trim (); // here there is a complicated logic to process return result;} private static string HandleString (string input, WhatToDo TheInstanceOfWhatToDo) {input = theinstanceoftodo (input ); return DateTime. now. toString ("yyyy-MM-dd HH: mm: ss ffffff") + input ;}}}

To sum up, a delegate is a method type definition with the same signature information (number and type of input parameters, and return parameter type) except the method name.

 

What is the purpose?

In the chestnuts above, it is not easy to reflect the purpose of delegation, but it is not difficult to understand a little: it has the role of splitting the number of particles in the method. At least as in the above example, you no longer need to make a bunch of judgments based on the ActoinType parameter. If there are more changes, the principle of opening and closing will not be violated. According to the defined WhatToDo, you can write a method to assign it to the delegated instance for debugging. (Of course, it is difficult to define a method for each extension, and there is little possibility of reuse. You don't have to worry about it. There is a simple way to do it later.

 

----------------------------------------- A disgusting separation line ------------------------------------------------

What is an event ?? I will explain it later, dig a hole, and fill it out later.

 

----------------------------------------- Separation line again ------------------------------------------------

 

Delegate to anonymous method

The basic skills are understood, and then the specific method of delegation is introduced. Fill in the first pit buried above.

To perform a delegate, you must name one delegate type, add another instance, and add the method pointed to by this instance. If you reference papi sauce, "do you mean abuse? Abuse or abuse? Abuse !"

At least. net framework does a little work for us. Because the input parameters of the method are limited, the. net framework can help us define the delegate type! Make good use of generics.

It is Func AND Action. Func has returned values, and Action has no returned values. See the following definition:

Func <TResult>

Func <T, TResult>

Func <T1, T2, TResult>

Func <T1, T2, T3 TResult>

.....

Func is to define N multiple-loaded delegation definitions (N is big, but it is impossible to use a method with so many input parameters ). From no input parameters, TResult is returned, and to n input parameters, TResult is returned, all defined.

See chestnuts

Static void Main (string [] args) {Func <string, DateTime, decimal, string> Method1 = MyMethod; Method1 ("Zhang San", DateTime. now, (decimal) 18.00);} public static string MyMethod (string parms1, DateTime parms2, decimal parms3) {return "I Am a string datetim decimal as the input parameter, returns the string method ";}

There is no much difference from the most traditional way of writing a delegate, but the definition of a delegate type is missing. Directly use the. net framework defined Func.

Similarly, Action is also a defined delegate, but no return type.

Action

Action <T1>

Action <T1, T2>

Action <T1, T2, T3>

It can still be used as a chestnut, even if it is easy to understand:

Static void Main (string [] args) {Action <string, DateTime, decimal> Method1 = MyMethod; Method1 ("Zhang San", DateTime. now, (decimal) 18.00);} public static void MyMethod (string parms1, DateTime parms2, decimal parms3) {Console. writeLine ("I Am a method that uses string datetim decimal string as the input parameter and does not return values ");}

 

----------------------------------------- Separation line again and again ------------------------------------------------

The change in delegation is certainly not just about how the. net framework helps us define several Delegate types. In this case, the anonymous method appears.

I don't want to define the delegate type. I just want to use the above Func, just as I can.

Using System; namespace Demo anonymous method {class Program {static void Main (string [] args) {Func <int, int, int> myMethodPlus = delegate (int a, int B) {return a + B ;}; Func <int, int, int> myMethodDivision = delegate (int a, int B) {if (B = 0) {return 0 ;} return a/B ;};}}}

This method is very elegant. You do not need to define methods separately. You can directly write the method body after the delegate instance equal sign. Because the chances of reuse of this method are close to 0. This is called an anonymous method, because it does not have a method name, but has an input parameter. If it returns a value, it is named.

PS. It is really hard for me to remember its syntax, because it is rarely used at work. What is the most common? See the following:

 

Convert an anonymous method to a lambda expression

Don't think about the anonymous method. The C # syntax is so sweet.

We have lambda expressions. This lambda is the Greek symbol lambda that comes in touch with high school mathematics. The delegation is more pleasing to the eye.

using System;namespace DemoLambda{    class Program    {        static void Main(string[] args)        {            Func<int, int, int> myMethodPlus = (int a, int b) => { return a + b; };            Func<int, int, int> myMethodDivision = (int a, int b) =>            {                if (b == 0)                {                    return 0;                }                return a / b;            };            int result1 = myMethodPlus(1, 1);            int result2 = myMethodDivision(4, 2);        }    }}

Yes. Even the delegate keyword translated by Baidu is missing at the beginning, which is replaced by =>. The syntax is (parameter 1, parameter 2, you can write parentheses if none of the parameters exist) =>{ method body };

Here, I understand the principles of Where (Func <T, bool>) and OrderBy (Func (T, TKey) that implement the GetEnumlator method.

 

Postscript:

I have been studying things from here for so many years, but I have never shared it. Finally, I am free to write a blog for the first time. For errors, thank you for making corrections.

 

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.