扩展方法和 Razor 页面
我在 app_code 中定义了一个扩展方法,如下所示。
public static class Extensions
{
public static string Hi(this object obj)
{
return "hi";
}
}
在 razor 页面中,任何东西都可以说 Hi :)
@Html.Hi();
@Request.Hi();
@this.Hi();
但是 @Hi()
不起作用。有没有办法让 @Hi()
工作?
I have defined an extension method in app_code like below.
public static class Extensions
{
public static string Hi(this object obj)
{
return "hi";
}
}
In the razor page, anything can say Hi :)
@Html.Hi();
@Request.Hi();
@this.Hi();
But @Hi()
doesn't work. Is there a way to make @Hi()
work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C# 只允许您调用由对象实例限定的扩展方法。
如果你有一个扩展你的类型的扩展方法,你不能“直接”调用它;你需要编写
this.ExtensionMethod()
。执行您要求的操作的唯一方法是创建一个继承
WebPage
(或 MVC 视图的WebViewPage
)的类,并更改您的 Razor 页面以继承该类(使用@inherits
指令)C# only allows you to call extension methods qualified by an object instance.
If you have an extension method that extends your type, you can't call it "directly"; you need to write
this.ExtensionMethod()
.The only way to do what you're asking for is to make a class which inherits
WebPage
(orWebViewPage
for MVC views) and change your Razor page to inherit that class (using the@inherits
directive)我认为你不能只调用@Hi()。很确定必须是@this.Hi()
I don't think you can call just @Hi(). Pretty sure is has to be @this.Hi()
就像正常场景一样,您必须将其包含在 using 中。剃刀语法是
Just like a normal scenario you have to include it in a using. the razor syntaz is