Ser*_*pia 3 c# extension-methods asp.net-mvc-2
我正在关注Pro ASP.Net MVC2书,字面上90%的一切对我来说都是新的.我觉得自己像糖果店里的小孩!:)
单元测试,依赖注入和其他东西对我创建的典型CRUD应用程序来说都是新的和非常陌生的.
现在我在测试时遇到了麻烦,这本书要求我们设计.
[Test]
public void Can_Generate_Links_To_Other_Pages()
{
// Arrange: We're going to extend the HtmlHelper class.
// It doesn't matter if the variable we use is null.
HtmlHelper html = null;
// Arrange: The helper should take a PagingInfo instance (that's
// a class we haven't yet defined) and a lambda to specify the URLs
PagingInfo pagingInfo = new PagingInfo
{
CurrentPage = 2,
TotalItems = 28,
ItemsPerPage = 10
};
Func<int, string> pageUrl = i => "Page" + i;
// Act
MvcHtmlString result = html.PageLinks(pagingInfo, pageUrl);
// Assert: Here's how it should format the links
result.ToString().ShouldEqual(@"<a href=""Page1"">1</a>
<a class=""selected"" href=""Page2"">2</a>
<a href=""Page3"">3</a>");
}
Run Code Online (Sandbox Code Playgroud)
我的html变量是一个HtmlHelper变量.似乎没有正确注册扩展方法PageLinks().
我在哪里检查这个?我意识到这个问题可能有点模糊,但任何帮助都会很精彩.
编辑:
显然这是我注册扩展方法的地方.虽然它似乎没有任何扩展.当我在上面的代码中输入时,至少intellisnse没有显示它.
public static class PagingHelpers
{
public static MvcHtmlString PageLinks(this HtmlHelper html, PagingInfo pagingInfo, Func<int, string> pageUrl)
{
StringBuilder result = new StringBuilder();
for (int i = 1; i <= pagingInfo.TotalPages; i++)
{
TagBuilder tag = new TagBuilder("a"); // Construct an <a> tag
tag.MergeAttribute("href", pageUrl(i));
tag.InnerHtml = i.ToString();
if (i == pagingInfo.CurrentPage)
tag.AddCssClass("selected");
result.AppendLine(tag.ToString());
}
return MvcHtmlString.Create(result.ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
此外,有人可以告诉我如何设置Visual Studio,因此它只是复制纯文本而没有荒谬的缩进?
编辑2: Woops!忘了键入错误:
错误1'System.Web.Mvc.HtmlHelper'不包含'PageLinks'的定义,并且没有扩展方法'PageLinks'接受类型'System.Web.Mvc.HtmlHelper'的第一个参数可以找到(你错过了吗?使用指令或程序集引用?)C:\ Users\Sergio\documents\visual studio 2010\Projects\SportsStore\SportsStore.UnitTests\ShowingPageLinks.cs 35 41 SportsStore.UnitTests
要使用扩展方法,您需要包含扩展方法类所在的命名空间.您还需要确保扩展方法类是静态的并且可以使用代码(例如,如果它在另一个程序集中,则不能是内部的).最后,请务必不要忘记this您要扩展的类型上的关键字.如果所有这些都已到位,你不应该看到问题.
| 归档时间: |
|
| 查看次数: |
2360 次 |
| 最近记录: |