我正在阅读《Pro MVC 2》一书,其中有一个关于为HtmlHelper类创建扩展方法的示例。
以下是代码示例:
public static MvcHtmlString PageLinks(this HtmlHelper html, PagingInfo pagingInfo, Func<int,string> pageUrl)
{
//Magic here.
}
以下是使用示例:
[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>")
}
编辑:已删除混淆本问题主旨的部分。
问题是:为什么示例代码使用 Func?我应该在什么情况下使用它?什么是 Func?
谢谢!
Func<T, T>
与扩展方法没有任何关系。你在问什么? - BoltClockPageLinks
的声明吗?第一个参数是this
,也就是一个扩展方法。该参数会绑定到调用中的html
对象上。 - Pete