Explanation of Func

前端 未结 4 1883
执笔经年
执笔经年 2020-12-07 09:02

I was wondering if someone could explain what Func is and how it is used with some clear examples.

4条回答
  •  日久生厌
    2020-12-07 09:16

    Are you familiar with delegates in general? I have a page about delegates and events which may help if not, although it's more geared towards explaining the differences between the two.

    Func is just a generic delegate - work out what it means in any particular situation by replacing the type parameters (T and TResult) with the corresponding type arguments (int and string) in the declaration. I've also renamed it to avoid confusion:

    string ExpandedFunc(int x)
    

    In other words, Func is a delegate which represents a function taking an int argument and returning a string.

    Func is often used in LINQ, both for projections and predicates (in the latter case, TResult is always bool). For example, you could use a Func to project a sequence of integers into a sequence of strings. Lambda expressions are usually used in LINQ to create the relevant delegates:

    Func projection = x => "Value=" + x;
    int[] values = { 3, 7, 10 };
    var strings = values.Select(projection);
    
    foreach (string s in strings)
    {
        Console.WriteLine(s);
    }
    

    Result:

    Value=3
    Value=7
    Value=10
    

提交回复
热议问题