C # example of basic anonymous method,

Source: Internet
Author: User

C # example of basic anonymous method,

This article describes the usage of the C # anonymous method in the form of examples and shares it with you for your reference. The details are as follows:

The anonymous method is a new feature of 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(string name)  {   return name.StartsWith("sunny", StringComparison.OrdinalIgnoreCase);  }}
View Code

This code initializes a string list at the beginning, and then searches for the string starting with "sunny" through the FindAll method of the list, finally, all the results found are output.

We need to focus on the FindAll method of List <T>. This method is a function with the Predicate <T> type and List <T> type returned. Note that Predicate <T> is a generic delegate that refers to functions that have only one T-type parameter and return a Boolean value. Using reflector and other tools, we can see that the definition of Predicate <T> is as follows:

    public delegate bool Predicate<T>(T obj); 

So far, we can guess the specific implementation of the FindAll method. For each element in List <T>, call the function referred to by Predicate <T>. If the function returns true, add it to the new List. After traversing all the elements, return the new list 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))    ret.Add(elem);  }  return ret; }
View Code

Therefore, for the above example, to call the FindAll method, we must first define a function whose parameter is of the string type and the return value is of the boolean type. In this function, we will make a condition judgment on the parameter, if the condition is met ("sunny" is used as the starting string), true is returned; otherwise, false is returned. Finally, pass the function as a parameter to FindAll. So we get the top code.

In the above example, we have to define a new function to call the FindAll method. In fact, this function is rarely used except for the FindAll method, you have to give it a name. If the FindAll method needs to be called in multiple programs, or in similar cases, a large number of "only one place to use" functions will appear in the entire program, making the code difficult to read and maintain.

Due to this problem, C #2.0 introduces the anonymous method. When implementing a method, developers only need to provide the parameter list (or even not) of the method and the specific implementation of the method, without worrying about the return value of the method, you do not need to name the method. The most important thing is to define the anonymous method only as needed to ensure the code is concise.

The anonymous method is defined only as needed. When defined, the delegate keyword is used, followed by the parameter list, and followed by a pair of function bodies included in curly brackets. The code above can be re-structured 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 NameMatches(string name)  //{  // return name.StartsWith("sunny",  //  StringComparison.OrdinalIgnoreCase);  //} }
View Code

At this point, we do not need the NameMatches method at all, and directly pass the anonymous method as a parameter to the FindAll method. In fact, the anonymous method still has a name, but we don't care about what name it should be, so. NET just gives us a name.

Anonymous methods are widely used in C #, because delegation as a function parameter is very common. We can also use anonymous methods when defining simple event processing processes. For example:

ServiceHost host = new ServiceHost(typeof(FileTransferImpl)); host.Opened += delegate(object sender, EventArgs e) {  Console.WriteLine("Service Opened."); };
View Code

The anonymous method can easily use local variables, which simplifies programming compared with the Individually Defined naming method. For example, in the preceding example, if the Main function defines an integer local variable (local variable) number, you can use the number variable in the delegate (string name) anonymous method definition.

As mentioned above, the parameter list can be omitted when an anonymous method is defined. The compiler can determine the function Signature Based on the delegate signature, and then just give the function a name. The following code demonstrates the usage:

Delegate void IntDelegate (int x); // The parameter-based definition method IntDelegate d2 = delegate (int p) {Console. writeLine (p) ;}; // The definition method without parameters (of course there is no returned value) IntDelegate d3 = delegate {Console. writeLine ("Hello. ");};
View Code

When using an anonymous method without parameters or returned values, pay attention to the following two points:

1. If you need to process parameters in your anonymous method, you cannot use the Declaration method that does not define the parameter list. That is, when defining an anonymous method, you need to provide a list of parameters.
2. An anonymous method without parameters and return values can be referred to by a delegate with any form of signature.

The first point above is obvious, because you have not defined the parameter list, there is no way to use the parameter; to describe the second point, 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 ambiguous between    *  Output(IntDelegate)    *    and    *  Output(StringDelegate)    */  Output(delegate { });  } } 
View Code

The code above cannot be compiled, because the compiler does not know whether to restore the anonymous delegate {} method to the IntDelegate function or to the StringDelegate function. The parameter list can only be explicitly specified to let the compiler know which Output function we want to call.

I hope this article will help you with C # programming.

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.