c# - 如何通过扩展方法使用对象而不实例化它?

标签 c#

我正在阅读一本 ASP.NET MVC 书籍。这是单元测试之一:

    [TestMethod]
    public void Can_Generate_Page_Links()
    {
        // arrange
        HtmlHelper myHelper = null;

        PagingInfo pagingInfo = new PagingInfo
        {
            CurrentPage = 2,
            TotalItems = 28,
            ItemsPerPage = 10
        };
        Func<int, string> pageUrlDelegate = i => "Page" + i;

        // act 
        MvcHtmlString result = myHelper.PageLinks(pagingInfo, pageUrlDelegate);

        // assert
        Assert.AreEqual(result.ToString(), 
            @"<a href=""Page1"">1</a>" + 
            @"<a href=""Page2"">2</a>" +
            @"<a href=""Page3"">3</a>"
        );
    }

注意如何 myHelper设置为null然后使用?唯一对 HtmlHelper 执行任何操作的代码这是扩展方法:

    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.Append(tag.ToString());
        }

        return MvcHtmlString.Create(result.ToString());
    }

扩展方法是否与允许我们使用设置为 null 的对象有关?如果没有,这里发生了什么?

最佳答案

你是对的。

只是因为扩展方法是语法糖。编译后,它本质上是这样的调用:

YourStaticClass.PageLinks(myHelper, pagingInfo, pageUrlDelegate);

请注意,在 PageLinks 方法中,从未使用 html 参数。如果是,它将抛出 NullReferenceException

关于c# - 如何通过扩展方法使用对象而不实例化它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20821352/

相关文章:

c# - SharpShell 服务器 .dll 未签名

c# - 尽管设置了精度,但 MSSQL 表中的十进制数会四舍五入

c# - XAudio2 与 C#

c# - CALayer initWithLayer : bound to default constructor by mistake? 我可以覆盖默认构造函数吗?

c# - 观察集合中项目的 PropertyChanged

c# - 如何在 ExecuteQueryDynamic 上的 LinqPad 上设置查询超时?

c# - 在 C# 中从 JSON 中检索特定值

c# - 用下划线替换字符串空格

c# - 关联失败。在 OIDC 身份验证期间在 Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler

c# - 如何使用 C# 在命令提示符下更改目录位置?