c# - 为什么 `w("hi")` doesn' t 工作但 `this.w("hi")` 工作?

标签 c# c#-4.0 razor

<分区>

Possible Duplicate:
Why is the 'this' keyword required to call an extension method from within the extended class

我想本地化我的 MVC 应用程序然后我想使用 w(message) 方法和作为 “flem”回答了here我有这段代码:

namespace System.Web.WebPages
{
    public static class Localization
    {
        public static string w(this WebPageBase page, string message)
        {
            return message;
        }
    }
}

但是在 razor page(page.cshtml) 我不能使用 @w("hi") 但是 @this.w("hi") 有效。 我想知道为什么 this.method() 有效但 method() 无效?

最佳答案

要调用静态方法,您必须指定该方法属于哪个类。

在您的例子中,因为这是一个扩展方法,this 指的是类型为 WebPageBase 的当前页面。所以 this.w("hi") 实际上和你写的一样:

@WebPageBase.w("hi")

...相当于:

@Localization.w(this, "hi")

关于c# - 为什么 `w("hi")` doesn' t 工作但 `this.w("hi")` 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12215546/

相关文章:

c# - 我应该给这个 cookie 什么域?

C# 允许同时控制台输入和输出

c# - 验证 Facebook 用户 ID 和访问 token 服务器端

asp.net-mvc - 如何在MVC3 Razor中禁用DropDownListFor?

asp.net-mvc - 将数据传递给 MVC 中的 @section

c# - Prism 事件聚合器。接收事件并再次发送

c# - 是否可以获取和修改文本框的标准系统上下文菜单?

asp.net - 点击回车时,文本框会聚焦在按钮上吗?

c# - 获取最后调用的方法的名称

asp.net - Razor 语法高亮