开发者

Extension Method and Razor Page

I have defined an extension method in app_code like below.

public static class Extensions
{
    public static string Hi(this object obj)
    {
        r开发者_如何学Pythoneturn "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?


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 (or WebViewPage for MVC views) and change your Razor page to inherit that class (using the @inherits directive)


I don't think you can call just @Hi(). Pretty sure is has to be @this.Hi()


Just like a normal scenario you have to include it in a using. the razor syntaz is

@using Namespace.Namespace
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜