开发者

please explain why this c# extension method works

I bought pro asp.net mv开发者_运维问答c2 framework book. I got stuck on page 122. I couldn't understand why it works.

I already emailed author, didnt get anything back yet. here's the code, can someone please explain to me why it works.

    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");
            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());
    }
}

this PageLinks helper method needs 3 parameters, but later in the book, when author call it,

<%: Html.PageLinks(
      new PagingInfo { CurrentPage = 2, TotalItems = 28, ItemsPerPage = 10 },
      i => Url.Action("List", new{ page = i})
) %>

author only passed in 2 parameters, HtmlHelper html is missing, but it sitll works. I couldn't figure out why, please help, thank you.


The first parameter to an extension method is the object it's called on. (Html in your example).

You can read more about extension methods on MSDN.


Extension methods differ from other methods in that they are

  • Declared static
  • The first parameter is the object on which it is called
  • The first parameter is prefixed by the this keyword

Further discussion can be found here: http://msdn.microsoft.com/en-us/library/bb383977.aspx


Since the first parameter is defined as <this Type name> as opposed to the usual the compiler knows to build it in such a way that the first parameter is automatically handled for you, and thus you only need to worry about those params if any that follow.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜