Can someone explain what the C# “Func” does?

后端 未结 8 2362
情话喂你
情话喂你 2020-12-13 12:34

I\'m reading the Pro MVC 2 book, and there is an example of creating an extension method for the HtmlHelper class.

Here the code example:

public stat         


        
8条回答
  •  囚心锁ツ
    2020-12-13 13:38

    A Func like

    Func pageUrl = i => "Page" + i;
    

    is a delegate accepting int as its sole parameter and returning a string. In this example, it accepts an int parameter with name i and returns the string "Page" + i which just concatenates a standard string representation of i to the string "Page".

    In general, Func accepts one parameter that is of type TSource and returns a parameter of type TResult. For example,

    Func toUpper = s => s.ToUpper();
    

    then you can say

    string upper = toUpper("hello, world!");
    

    or

    Func month = d => d.Month;
    

    so you can say

    int m = month(new DateTime(3, 15, 2011));
    

提交回复
热议问题