Implementing anonymous functions and RAMDA expressions for delegates

Source: Internet
Author: User

* * Delegate (delegate): A data type that represents a method. Indirectly derived from System.Delegate

A delegate is a reference type, but it does not have to be instantiated with new. Pass the name directly instead of the real instantiation. This is a new syntax that c#2.0 begins to support, and becomes a delegate inference (delegate inference)

1 namespaceDelegateex2 {  3     //Delegate Declaration4      Public Delegate BOOLComparisonhandler (intFirstintsecond); 5   6      Public Static classDelegatesample7{//  8          Public Static voidBubblesort (int[] items, Comparisonhandler comparisonmethod)9         {  Ten             inti;  One             intJ;  A             inttemp;  -             if(Items = =NULL)   -             {   the                 return;  -             }   -             if(Comparisonmethod = =NULL)   -             {   +                 Throw NewArgumentNullException ("Comparisonmethod");  -             }   +    A              for(i = items.) Length-1; I >=0; i--)   at             {   -                  for(j =1; J <= I; J + +)   -                 {   -                     //using a delegate instance -                     if(Comparisonmethod (Items[j-1], items[j])) -                     {   intemp = items[j-1];  -Items[j-1] =Items[j];  toITEMS[J] =temp;  +                     }   -                 }   the             }   *         }   $         //parameter GreaterThan for matching delegates (int first, int second)Panax Notoginseng          Public Static BOOLGreaterThan (intFirstintsecond) -         {   the             returnFirst >second;  +         }   A     }   the     class Program +     {   -         Static voidMain (string[] args) $         {   $             int[] items =New int[ -];  -Random random =NewRandom ();  -              for(inti =0; I < items. Length; i++)   the             {   -Items[i] = random. Next (1, -); Wuyi             }   the             //passing a delegate instance as a parameter - Delegatesample.bubblesort (Items,delegatesample.greaterthan);  Wu    -              for(inti =0; I < items. Length; i++)   About             {   $Console.Write ("{0}", Items[i]);  -             }   - Console.readkey ();  -         }   A     }   +}

* * Anonymous method: There is no actual way to declare a delegate instance, or their definition is directly embedded in the code.

1 Static voidMain (string[] args)2 {  3     int[] items =New int[5]; 4Random random =NewRandom (); 5 Comparisonhandler Comparisonmethod; 6   7      for(inti =0; I < items. Length; i++)  8     {  9Items[i] = random. Next (1, -); Ten     }   One   //the definition of a delegate is embedded directly in the code.  AComparisonmethod =Delegate(intFirstintsecond) -     {   -         returnFirst <second;  the     };  - Bubblesort (Items,comparisonmethod);  -    -      for(inti =0; I < items. Length; i++)   +     {   -Console.Write ("{0}", Items[i]);  +     }   A Console.readkey ();  at}

Or use a more straightforward approach:

1 bubblesort (items,  2     delegate(intint  second)   3 {  4     return first < second;   5 });  

Note that in any case, the parameter and the return value type must be compatible with the data type of the delegate.

* The anonymous method is allowed to omit the argument list, but the return value type needs to be consistent with the delegate.

* * System-defined delegate:

System.Func represents a delegate with a return type in. NET 3.5

System.Action represents a delegate with no return type.

You cannot assign a delegate type to a variable of another delegate type, even if the type parameter matches.

* Use variability for delegates [not understood]

action<Object> broadaction=Delegate(Objectdata) {Console.WriteLine (data);} Action<string> narrowaction=broadaction; Func<string>narrowfunction=Delegate(){returnConsole.WriteLine ();}; Func<Object> broadfunction=narrowaction; Func<Object,string>func1=Degate (Objectdata) {returndata. ToString ();}; Func<string,Object>func2=fun1;

**lamda expression (keyword = =): Divided into Lamda expressions and LAMDA statements

[CSharp]View Plaincopy
1 bubblesort (items,  2                 delegate(intint  second)   3             {  4                 return first < second;   5             });  

The equivalent LAMDA statement (for)

1 bubblesort (items,  2     (intint second) =  3    {   4         return First < second;   5     }  6

* Omit parameter types: Typically, the statement LAMDA does not require a parameter type, as long as the compiler can infer the parameter type, or it can implicitly convert the parameter type to the desired data type. If the type is to be developed, the type must exactly match the delegate type. As long as the LAMDA statement contains a type, all types are added.

1 bubblesort (items,  2     (first,second) =  3    {  4          return first < second;   5     }  6 );  

*c# requires a pair of parentheses to enclose the parameter class table of the LAMDA expression, regardless of whether the data type of the parameter is specified. Another rule for parentheses is that when the compiler can infer the data type, and there is only one input parameter, the statement LAMDA can be without parentheses.

Func<string> getuserinput=

() =

{

string input;;

Do

{Input=console.readline ();}

while (input. Trim () ==0);

return input;

}

*lamda expression (satisfying ... Conditions


    1. Bubblesort (Items,
    2. (int First, int second) +-first < second);


**LAMDA expression itself has no type

So . the operator is not compiled, and the method that invokes object is not.

Cannot appear on the left side of IS

Once the LAMDA expression is assigned or transformed, there is a type of LAMDA expression that is informally said

You cannot assign a variable to an implicit type

If the purpose is outside the LAMDA expression, C # does not allow the use of a jump statement (Break,continue,goto) inside an anonymous function

* External variables: External declarations of LAMDA expressions (including parameters), but local variables for internal snapping (access) of LAMDA expressions are called external variables. This is also an external variable.

int Comparisoncount= 0;

...

Bubblesort (Item,

(int first, int second) =

{

Comparisoncount+ +;

Return first<second;

}

);

Console.WriteLine (comparisoncount);

* * expression tree [not understood]

"Interpreting" is an important motivation for C # to introduce the concept of expression tree (trees). If a LAMDA expression represents data related to an expression, rather than compiled code, the LAMDA expression is an expression tree. Since the expression tree represents data rather than compiled code, it is possible to convert the data into an alternative format. For example, convert to SQL code.

Persons. Where (Person=>person. Name.toupper () = = "INIGO MONTOYA")

Select *from person where upper (Name) = ' INIGO MONTOYA '

Implementing anonymous functions and RAMDA expressions for delegates

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.