Examples of anonymous methods for C # Basics Tutorial

Source: Internet
Author: User

This article explains the use of anonymous methods of C # in the form of examples and shares them for your reference. Specific as follows:

The anonymous method is a new language feature for C # 2.0. First, let's look at the simplest example:

Class program{static void Main (string[] args) {  list<string> names = new list<string> ();  Names. ADD ("Sunny Chen");  Names. ADD ("Kitty Wang");  Names. ADD ("Sunny Crystal");  List<string> found = names. FindAll (New predicate<string> (namematches));  if (found! = null)  {   foreach (string str in found)    Console.WriteLine (str);}  } static bool Namematches (ST Ring name) {  return name. StartsWith ("Sunny", stringcomparison.ordinalignorecase); }}

This code initializes a string list at the beginning, and then uses the FindAll method of the list to find the string starting with "sunny" and finally outputs all the results found.

We need to highlight the FindAll method of list<t>. This method is a function with a parameter of type predicate<t> and a return value of type list<t>. Note,predicate<t> is a generic delegate that refers to functions that have only one parameter of type T and the return value is a Boolean type. With tools such as reflector, we can see the definition of predicate<t> as follows:

Public delegate bool Predicate<t> (T obj);

At this point we can also guess how to implement the FindAll method. That is, for each element in list<t>, the function referred to by predicate<t> is called, and if the function returns True, it is added to the newly created list. After all the elements have been traversed, the newly created list is returned to the caller. As follows:

Public list<t> findall<t> (predicate<t> match) {list<t> ret = new list<t> (); foreach (T elem In items) {  if (match (Elem))   

Therefore, for the above example, to invoke the FindAll method, we must first define a function with a string type, return a Boolean type, in which the parameters are conditionally judged, and if the condition is met (that is, "sunny" as the starting string), then it returns true , otherwise false is returned. Finally, the function is passed as a parameter to the FindAll. So you get the most up-to-the-top code.

In the above example, in order to invoke the FindAll method, we have to define a new function, in fact, this function in addition to the FindAll method to use, and other places are almost rarely used to it, you have to give it a name. If there are multiple calls to the FindAll method in the program, or a similar situation, then the entire program will have a large number of "only one place to use" function, making the code difficult to read and maintain.

Because of this problem, C # 2.0 introduces an anonymous method. When implementing a method, the developer only needs to give a list of the parameters of the method (or even not) and how to implement the method, without needing to care about the return value of the method, not to give the method a name. Most crucially, the anonymity method is defined only where it is needed, guaranteeing the simplicity of the code.

An anonymous method is defined only where it is needed, defined by using the delegate keyword, followed by a parameter list, followed by a function body that is included with a pair of curly braces. The above code can be re-formed in the following form:

Class program{static void Main (string[] args) {  list<string> names = new list<string> ();  Names. ADD ("Sunny Chen");  Names. ADD ("Kitty Wang");  Names. ADD ("Sunny Crystal");  List<string> found = names. FindAll (   Delegate (string name)   {    return name. StartsWith ("Sunny", stringcomparison.ordinalignorecase);   });  if (found! = null)  {   foreach (string str in found)    Console.WriteLine (str);}  }//static bool NAMEMATC Hes (string name)//{//return name. StartsWith ("Sunny",//  

At this point, we do not need the Namematches method at all, directly passing the anonymous method as a parameter to the FindAll method. In fact, the anonymous method itself still has a name, but we do not care what it is to take what name, so. NET helped us take a name.

Anonymous methods are widely used in C # because delegates are very common as function parameters. We can also use anonymous methods when defining simple event-handling procedures. Like what:

ServiceHost host = new ServiceHost (typeof (Filetransferimpl)); Opened + = Delegate (object sender, EventArgs e) {Console.WriteLine ("Service opened.");

Anonymous methods make it easy to use local variables, which simplifies programming compared to a separately defined naming method. For example above, if the main function defines an integer local variable (local variable) number, you can use the number variable in the anonymous method definition of delegate (string name).

As mentioned above, even the parameter list can be omitted when defining an anonymous method. Because the compiler can determine the signature of a function based on the signature of the delegate, then just give the function a name. The following code shows how this is used:

delegate void intdelegate (int x);//with parameters defined in Intdelegate d2 = delegate (int p) {Console.WriteLine (P);};//without parameters (of course, no return return value) intdelegate D3 = delegate {Console.WriteLine ("Hello.");};

When using anonymous method definitions without parameters and return values, the following two points need to be noted:

1. If you need to process parameters in your anonymous method, you cannot use a declaration that does not define a parameter list. That is, when you define an anonymous method, you need to give a list of parameters.

2. Anonymous methods without parameters and return values can be referred to by delegates with any form of signature.

The 1th above is obvious, because you do not define a parameter list, there is no way to use parameters; to illustrate the 2nd, we can look at the following code:

Class program{delegate void intdelegate (int x), delegate void Stringdelegate (string y), static void Output (Intdelegate ID {} static void Output (Stringdelegate sd) {} static void Main (string[] args) {/   * * Error:the call is Ambiguou s between   *  output (intdelegate)   *    and   *  output (stringdelegate)   *  /output ( delegate {}); }}

The code above cannot be compiled because the compiler does not know whether the anonymous method of delegate {} should be restored to a function referred to by intdelegate or to a function referred to by stringdelegate. The argument list can only be given explicitly at this point so that the compiler knows which output function we want to invoke.

I hope this article is helpful to everyone's C # program design

In addition to the Declaration, Running GuestArticles are original, reproduced please link to the form of the address of this article
Examples of anonymous methods for C # Basics Tutorial

This address: http://www.paobuke.com/develop/c-develop/pbk23547.html






Related content for iobservable implementing its own operator (detailed) How to handle a file or assembly error when calling a DLL in C # The application of the abstract Factory mode of C # design pattern programming realizes ASP. NET no refresh download and prompt download complete development idea
C # Method of reading and writing XML files through a DataSet C # traverse all drives under the operating system C # Implement a method for sending simple HTTP requests C # Algorithm of the full permutation recursive algorithm example explained

Examples of anonymous methods for C # Basics Tutorial

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.