为什么我不能在Razor WebGrid的委托中使用我的扩展方法?

本文关键字:我的 扩展 方法 不能 Razor WebGrid 为什么 | 更新日期: 2023-09-27 18:05:36

我使用MVC 3引入的WebGrid,但不能不能在传递format参数委托时应用我自己的扩展方法。

使用:

Grid.Column("MyProperty", "MyProperty", 
format: @<span class="something">@item.MyProperty.MyExtensionMethodForString()</span>)

I got

ERROR: 'string' does not contain a definition for 'MyExtensionMethodForString'

我试过铸造,但没有用

Grid.Column("MyProperty", "MyProperty", 
format: @<span class="something">@((string)(item.MyProperty).MyExtensionMethodForString())</span>)

如果我使用标准方法,它可以工作:

Grid.Column("MyProperty", "MyProperty", 
format: @<span class="something">@(Utils.MyExtensionMethodForString(item.MyProperty))</span>)

我也试过把扩展名放在同一个命名空间中,但没有结果。

我如何使用我心爱的扩展?

编辑:名称空间本身不是问题,扩展可用于所有视图和类的名称空间,我可以在同一视图中使用它,没有问题。问题是在委托中使用它

为什么我不能在Razor WebGrid的委托中使用我的扩展方法?

这不是WebGrid或Razor的限制。这是c# dynamic类型的一个限制。不能在动态上使用扩展方法。格式帮助器接受一个Func<dynamic, object>作为参数,因此item参数是一个动态类型。

几年前我写过这个问题

这对我来说很好。静态类:

public static class TestExtensions
{
    public static string Foo(this HtmlHelper html, Func<object, HelperResult> func)
    {
        return func(null).ToHtmlString();
    }
    public static string MyStringExtension(this string s)
    {
        return s.ToUpper();
    }
}

Index.cshtml:

@using MvcApplication1.Controllers
@Html.Foo(@<text>@Html.Raw("Hello")</text>)

页面打印出:

你好

但是,这个版本的Index.cshtml:

@using MvcApplication1.Controllers
@Html.Foo(@<text>@("Hello".MyStringExtension())</text>)

打印出错误信息:

CS1061: 'string'不包含'MyStringExtension'的定义,并且没有扩展方法'MyStringExtension'接受'string'类型的第一个参数可以找到(您是否缺少using指令或程序集引用?)

所以我怀疑Jon是对的,这是Razor的限制。(为什么它与HtmlHelper一起工作让我有点困惑)

通过研究为什么下面一行会抛出相同的错误发现了这个SO问题:

@a.GetAttribute<ActionLabelAttribute>().ActionLabel

可以很容易地通过将这行括在括号中进行更正,如下所示:

@(a.GetAttribute<ActionLabelAttribute>().ActionLabel)

注意:GetAttribute扩展方法来自这里