Func and Action

Source: Internet
Author: User

Generally, if we want to use a delegate, we generally declare a delegate type first, for example:

private delegate string Say();

String indicates that the return type of the delegate method is string, and the delegate nameSayThere is no parameter later, indicating that the corresponding method does not input the parameter.

Write a method that applies to the delegate:

     public static string SayHello()        {            return "Hello";        }

Last call:

       static void Main(string[] args)        {            Say say = SayHello;            Console.WriteLine(say());        }

Here we declare the delegate first, and then pass the method to the delegate. Is there a way to not define the delegate variable?

The answer is yes. We can useFunc.

FuncIs the built-in delegate in. NET, which has many heavy loads.

Func <TResult>: No input parameter. The return type isTResult. Just like the above Say delegate, you can useFunc <string>The call is as follows:

      static void Main(string[] args)        {            Func<string> say = SayHello;            //Say say = SayHello;            Console.WriteLine(say());        }

How about it?FuncIt's easy. Take a lookFuncOther reloads.

Func <T, TResult>Delegate: There is an input parameterT, The return type isTResult. For example:

// The input parameter type of the delegate is string, and the return type of the method is int Func <string, int> a = Count;
// Corresponding method public int Count (string num) {return Convert. ToInt32 (num );}

Func <T1, T2, TResult>Delegate: There are two input parameters:T1AndT2, The return type isTResult.

SimilarlyFunc (T1, T2, T3, TResult)Delegate,Func (T1, T2, T3, T4, TResult)Delegate. The usage is similar. All parameters are input parameters of the method, and the last one is the return type of the method.

FuncIt can also be used with anonymous methods, for example:

        public static void Main()        {            Func<string, int, string[]> extractMeth = delegate(string s, int i)            {                char[] delimiters = new char[] { ' ' };                return i > 0 ? s.Split(delimiters, i) : s.Split(delimiters);            };            string title = "The Scarlet Letter";            // Use Func instance to call ExtractWords method and display result            foreach (string word in extractMeth(title, 5))                Console.WriteLine(word);        }

It can also be connectedLambdaExpression

  public static void Main()   {      char[] separators = new char[] {' '};      Func<string, int, string[]> extract = (s, i) =>            i > 0 ? s.Split(separators, i) : s.Split(separators) ;      string title = "The Scarlet Letter";      // Use Func instance to call ExtractWords method and display result      foreach (string word in extract(title, 5))         Console.WriteLine(word);   }

FuncAll of them have a return type. What if our method does not have a return type? ThenActionIt's about to go viral.

ActionDelegate: no input parameter or return type, namely, Void. For example:

       static void Main(string[] args)        {            Action say = SayHello;
say(); } public static void SayHello( ) { Console.WriteLine("Say Hello"); }

Action <T>Delegate: the input parameter isT, No return type. For example:

      static void Main(string[] args)        {            Action<string> say = SayHello;            say("Hello");        }        public static void SayHello(string word )        {            Console.WriteLine(word);        }

Action <T1, T2>Delegate: two input parameters:T1AndT2, No return type.

ActionThere are also many other overloads. Each overload uses the same method, but the number of input parameters of the method is different.

ActuallyActionAndFuncThe difference is that one has a return type and one has no return type. Of courseActionYou can also use the anonymous method andLambdaExpression.

Anonymous method:

    static void Main(string[] args)        {            Action<string> say = delegate(string word)            {                Console.WriteLine(word);            };            say("Hello Word");        }

LambdaExpression:

     static void Main(string[] args)        {            Action<string> say = s => Console.WriteLine(s);            say("Hello Word");        }

 

 

 

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.