扩展方法和剃刀页面 [英] Extension Method and Razor Page

查看:81
本文介绍了扩展方法和剃刀页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在app_code中定义了一个扩展方法,如下所示.

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

但是@Hi()不起作用.有没有办法使@Hi()工作?

But @Hi() doesn't work. Is there a way to make @Hi() work?

推荐答案

C#仅允许您调用对象实例限定的扩展方法.
如果您有一个扩展方法来扩展您的类型,则不能直接"调用它.您需要写this.ExtensionMethod().

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().

要做的唯一方法是创建一个继承WebPage的类(对于MVC视图,则为WebViewPage),然后将Razor页面更改为继承该类(使用@inherits指令)

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)

这篇关于扩展方法和剃刀页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆