【发布时间】:2011-03-15 17:23:06
【问题描述】:
我正在阅读 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
pageUrl = i => "Page1" + i;生产线正在做。 -
我不明白。
Func<T, T>与扩展方法无关。你在问什么? -
你是说
PageLinks的声明?第一个参数是this,即扩展方法。该参数被绑定到调用中的html对象。 -
注意:请忽略扩展方法位,我写错了问题。我主要想了解一下Func是什么,以及为什么这个例子选择使用它。另外,什么时候应该使用它。我提供了示例,仅用于上下文目的。
-
注:扩展方法的引用纯粹是因为在MVC书中Func在介绍它们的章节中首次使用。