What is Func, how and when is it used

前端 未结 8 1773
悲哀的现实
悲哀的现实 2020-11-27 10:53

What is Func<> and what is it used for?

相关标签:
8条回答
  • 2020-11-27 11:12

    Func<T> is a predefined delegate type for a method that returns some value of the type T.

    In other words, you can use this type to reference a method that returns some value of T. E.g.

    public static string GetMessage() { return "Hello world"; }
    

    may be referenced like this

    Func<string> f = GetMessage;
    
    0 讨论(0)
  • 2020-11-27 11:12

    Think of it as a placeholder. It can be quite useful when you have code that follows a certain pattern but need not be tied to any particular functionality.

    For example, consider the Enumerable.Select extension method.

    • The pattern is: for every item in a sequence, select some value from that item (e.g., a property) and create a new sequence consisting of these values.
    • The placeholder is: some selector function that actually gets the values for the sequence described above.

    This method takes a Func<T, TResult> instead of any concrete function. This allows it to be used in any context where the above pattern applies.

    So for example, say I have a List<Person> and I want just the name of every person in the list. I can do this:

    var names = people.Select(p => p.Name);
    

    Or say I want the age of every person:

    var ages = people.Select(p => p.Age);
    

    Right away, you can see how I was able to leverage the same code representing a pattern (with Select) with two different functions (p => p.Name and p => p.Age).

    The alternative would be to write a different version of Select every time you wanted to scan a sequence for a different kind of value. So to achieve the same effect as above, I would need:

    // Presumably, the code inside these two methods would look almost identical;
    // the only difference would be the part that actually selects a value
    // based on a Person.
    var names = GetPersonNames(people);
    var ages = GetPersonAges(people);
    

    With a delegate acting as placeholder, I free myself from having to write out the same pattern over and over in cases like this.

    0 讨论(0)
提交回复
热议问题