有人可以解释一下C#"Func <T,T>"的作用吗?

39 c# func

我正在阅读Pro MVC 2书,并且有一个为HtmlHelper类创建扩展方法的示例.

这里是代码示例:

public static MvcHtmlString PageLinks(this HtmlHelper html, PagingInfo pagingInfo, Func<int,string> pageUrl)
{
    //Magic here.
}
Run Code Online (Sandbox Code Playgroud)

以下是一个示例用法:

[Test]
public void Can_Generate_Links_To_Other_Pages()
{
    //Arrange: We're going to extend the Html helper class.
    //It doesn't matter if the variable we use is null            
    HtmlHelper html = null;

    PagingInfo pagingInfo = PagingInfo(){
        CurrentPage = 2,
        TotalItems = 28,
        ItemsPerPage = 10
    };

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

    //Act: Here's how it should format the links.
    MvcHtmlString result = html.PageLinks(pagingInfo, pageUrl);

    //Assert:
    result.ToString().ShouldEqual(@"<a href=""Page1"">1</a><a href=""Page2"">2</a><a href=""Page3"">3</a>")           

}
Run Code Online (Sandbox Code Playgroud)

编辑:这混淆去除部这个问题.

问题是:为什么使用Func的例子?我应该什么时候使用它?什么是Func?

谢谢!

jas*_*son 106

一个Func<int, string>

Func<int, String> pageUrl = i => "Page" + i;
Run Code Online (Sandbox Code Playgroud)

是一个委托接受int作为其唯一参数并返回一个string.在此示例中,它接受int带有name 的参数,i并返回"Page" + i仅将标准字符串表示形式连接到字符串i的字符串"Page".

通常,Func<TSource, TResult>接受一个类型TSource的参数并返回类型的参数TResult.例如,

Func<string, string> toUpper = s => s.ToUpper();
Run Code Online (Sandbox Code Playgroud)

那么你可以说

string upper = toUpper("hello, world!");
Run Code Online (Sandbox Code Playgroud)

要么

Func<DateTime, int> month = d => d.Month;
Run Code Online (Sandbox Code Playgroud)

所以你可以说

int m = month(new DateTime(3, 15, 2011));
Run Code Online (Sandbox Code Playgroud)


Bol*_*ock 13

Func<int, String>表示一个回调方法,它接受一个int参数并返回一个String结果.

以下表达式,称为lambda表达式:

Func<int, String> pageUrl = i => "Page" + i;
Run Code Online (Sandbox Code Playgroud)

扩展到这样的东西:

Func<int, String> pageUrl = delegate(int i)
{
    return "Page" + i;
}
Run Code Online (Sandbox Code Playgroud)