为什么我不能用我的扩展方法在剃刀的WebGrid委托 [英] Why can't I use my extension method in a delegate in the Razor WebGrid
问题描述
我使用引进的WebGrid的MVC 3,但可通过对格式
参数的委托时,不是不能申请我自己的扩展方法。
I'm using the MVC 3 introduced WebGrid, but can't can't apply my own extension methods when passing a delegate for the format
param.
使用:
Grid.Column("MyProperty", "MyProperty",
format: @<span class="something">@item.MyProperty.MyExtensionMethodForString()</span>)
我
ERROR: 'string' does not contain a definition for 'MyExtensionMethodForString'
我试过铸造,而不是利用
I've tried casting, not to avail
Grid.Column("MyProperty", "MyProperty",
format: @<span class="something">@((string)(item.MyProperty).MyExtensionMethodForString())</span>)
如果我使用一个标准的方法,它的工作原理:
If I use an standard method, it works:
Grid.Column("MyProperty", "MyProperty",
format: @<span class="something">@(Utils.MyExtensionMethodForString(item.MyProperty))</span>)
我也试图把扩展在同一个命名空间,没有任何结果。
I've also tried to put the extension in the same namespace, with no results.
如何我可以用我心爱的扩展?
修改:这不是问题,这里的扩展可用于所有的意见和类的名称空间,我可以在同一视图中使用它没有问题的命名空间本身。在委托使用时出了问题。
Edit: The namespace per se it's not the problem, the namespace where the extension is available for all the views and classes, and I can use it in the same view without problem. The problem is when using it in the delegate.
推荐答案
这是不是的WebGrid或剃刀的限制。这是C#的限制动态
键入。不能在动态使用扩展方法。格式助手需要一个 Func键&LT;动态,对象&gt;
作为参数,所以项目
参数是一个动态的类型。
This is not a limitation of the WebGrid or Razor. It's a limitation of the C# dynamic
type. You cannot use extension methods on dynamic. The format helper takes a Func<dynamic, object>
as an argument, so the item
parameter is a dynamic type.
<我一个href=\"http://www.mikesdotnetting.com/Article/171/Why-You-Can%27t-Use-Extension-Methods-With-A-WebGrid\"相对=nofollow> 几年前写了一篇关于这个确切的问题。
I wrote about this exact issue a couple of years ago.
这篇关于为什么我不能用我的扩展方法在剃刀的WebGrid委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!