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

后端 未结 8 2363
情话喂你
情话喂你 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:14

    The Func<int, string> line that you are inquiring about is known as a lambda expression.

    Func<int, String> pageUrl = i => "Page" + i;
    

    This line can be described as a function that takes an int parameter (i) and returns a string "Page" + i;

    It can be re-written as:

    delegate(int i)
    {
        return "Page" + i;
    }
    
    0 讨论(0)
  • 2020-12-13 13:17

    Func<T, TResult>: Encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter. See this page for more details and examples. :-)

    0 讨论(0)
  • 2020-12-13 13:18

    Because the PageLinks method is an Extension Method.

    In extension method, the first parameter starts with this keyword to indicate that it is an Extension method on the type represented by the first parameter.

    The Func<T1, T2> is a delegate which represents a transformation from type T1 to type T2. So basically, your PageLinks method will apply that transformation to int to produce a string.

    0 讨论(0)
  • 2020-12-13 13:31

    Func<int, String> means a callback method that takes an int parameter and returns a String as the result.

    The following expression, which is known as a lambda expression:

    Func<int, String> pageUrl = i => "Page" + i;
    

    expands to something like this:

    Func<int, String> pageUrl = delegate(int i)
    {
        return "Page" + i;
    }
    
    0 讨论(0)
  • 2020-12-13 13:35

    Create your own

    Func<int,string> myfunc; 
    

    then right click Func to view definition. You will see it is a delegate underneith

    public delegate TResult Func<in T, out TResult>(T arg);
    
    0 讨论(0)
  • 2020-12-13 13:38

    A Func<int, string> like

    Func<int, String> 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<TSource, TResult> accepts one parameter that is of type TSource and returns a parameter of type TResult. For example,

    Func<string, string> toUpper = s => s.ToUpper();
    

    then you can say

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

    or

    Func<DateTime, int> month = d => d.Month;
    

    so you can say

    int m = month(new DateTime(3, 15, 2011));
    
    0 讨论(0)
提交回复
热议问题