Anonymous methods, lambda expressions, higher-order functions

Source: Internet
Author: User

Original: Anonymous method, lambda expression, higher order function

    • Anonymous methods

C#2.0 introduces anonymous methods, eliminating the need to create separate methods, thus reducing the coding overhead required. is commonly used to associate delegates with anonymous methods, such as

1. Use delegates and method associations:

This.btnRefresh.Click + =NewSystem.EventHandler (This.btnrefresh_click);
Private voidBtnrefresh_click (Objectsender, EventArgs e)
{
Binddata ();
}

2. Use delegates and anonymous method associations:
This.btnRefresh.Click + = Delegate (object sender, EventArgs e) {binddata ();};

There is no doubt that Code 2 is more concise if the associated method is a "one word method" (actually the compiler has created a method like Btnrefresh_click for us behind the scenes).

    • Anonymous method omitting argument list

When you define an anonymous method, the argument list can be omitted, and the compiler can determine the signature of the function based on the signature of the delegate. For example
delegate void Func (int x);
With parameters
Func f1= Delegate (int p) {Console.Write (P);}
With no parameters
Func F2 = delegate {Console.Write ("he");}//compiler automatically infers function signature with int parameter
Using anonymous methods without parameters, note the issue
One is because there are no parameters, so parameters cannot be used within a method.
Second, there are situations where anonymous methods cannot be used, and there are ambiguous problems, such as
Public Thread (Parameterizedthreadstart start);
Public Thread (ThreadStart start);
While//public delegate void Parameterizedthreadstart (object obj);
public delegate void ThreadStart ();
So use
Thread thread = new Thread (
delegate {Sh. Lockmyself (); }
);
There's going to be problems.
Error the call is ambiguous between the following methods or properties: ' System.Threading.Thread.Thread (system.threading . ThreadStart) ' and ' System.Threading.Thread.Thread (System.Threading.ParameterizedThreadStart) '

The compiler does not know what function the anonymous method of delegate {} should be restored to, and the workaround is to explicitly give the argument list so that the compiler knows you want to use that function:
Thread thread = new Thread (
Delegate () {sh. Lockmyself (); }
);

Lambda expression:
Thread thread = new Thread (
() =
{
Sh. Lockmyself ();
}
);

    • lambda expression

The

LAMBDA expression provides a more concise, functional syntax for writing anonymous methods, but the result becomes extremely useful when writing LINQ query expressions. Because they provide a very compact and class-safe way to write a function that can be passed as a parameter in a later operation.
Lambda expressions and anonymous methods are actually one thing. The only difference is that they have different grammatical expressions. Lambda expressions are a further evolutionary aspect of grammar. In essence, they are one thing. Their role is: to produce a method. That is: Inline method.

Books is a System.Collections.Generic.List type, that is list<book>, there is a Find method
Use the anonymous method:              books. Find (Delegate (Book book) {Return book. price <  50 ;}); The
uses a lambda expression:       books. Find (Book=>book. PRICE<50);
Book is the input parameter; = = read as go to, is the lambda operator; Price<50 is either an expression or a block of statements. The input parameters in the
lambda expression omit the parameter type because the current Find extension method object is books, and the compiler automatically infers that the book parameter belongs to the book type.
Compare another example:

//using anonymous Methods
string[] List= New string[] { "ABC", " A", "Java" };
string[] alist=Array.findall (list,
Delegate(stringS
{
returnS.indexof ("a") >= 0;
}
);
foreach (stringvarinchalist)
{
Console.WriteLine (Var);
}

//using lambda expressions
string[] List= New string[] { "ABC", " A", "Java"};
string[] alist=Array.findall (list, S=(S.indexof ("a") >= 0));

Examples of lambda expressions:

//The type of x is omitted, and the compiler can infer it from context, followed by an expression
x=x+1
Deleage (intx) {returnx+1;}
//Followed by a statement block
x={returnx+1;}
Delegate(intx) {returnx+1;}
//input parameters can also be type, with type don't forget parentheses oh
(intx)=x+1
Delegate(intx) {returnx+1;}
//can also be multiple input parameters, comma-delimited, don't forget the parentheses
(x, y)=x+y
Delegate(intx,inty) {returnx+Y;}
//no argument is ok
() = 1
Delegate(){return 1;}

Higher order functions (Higher-order function)

Refers to a function that takes another function as a parameter or a return value.
For example, there are many static higher-order functions in the System.Array class, and the ConvertAll method is one of the most commonly used high-order functions:

Private StaticDateTime Stringtodatetime (strings) {
returnDateTime.ParseExact (s),"YYYY-MM-DD", NULL);
}

Static voidMain (string[] args) {
string[] datestrings= New string[] {
"2009-01-01", "2009-01-02", "2009-01-03",
"2009-01-04", "2009-01-05", "2009-01-06",
};
//ConvertAll maps An array to another array, and new converter constructs a delegate object
//similar to New System.EventHandler (This.btnrefresh_click);
datetime[] Dates=Array.convertall<string, DateTime>(
Datestrings,NewConverter<string, DateTime>(Stringtodatetime));
}


//in C # 2.0, an anonymous method is introduced to construct a delegate object:

Datetime[] Dates=Array.convertall<string, DateTime>(
Datestrings,
Delegate(strings) {
returnDateTime.ParseExact (s),"YYYY-MM-DD", NULL);
});

//with the addition of language features such as lambda expressions and extension methods, as well as the automatic judgment of the paradigm type, the use of anonymous methods in C # 3.0 is more concise and even the same as Ruby's syntax
IEnumerable<DateTime>dates=Datestrings.select (
S=DateTime.ParseExact (s),"YYYY-MM-DD", NULL));

Reference
Http://blog.csdn.net/shouyenet1/archive/2009/04/28/4133114.aspx
Http://blog.joycode.com/scottgu/archive/2007/04/09/100744.aspx
Http://www.infoq.com/cn/articles/higher-order-function
Http://www.infoq.com/cn/articles/higher-order-function

Anonymous methods, lambda expressions, higher-order functions

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.