为什么我不能用我的扩展方法在剃刀的WebGrid委托 [英] Why can't I use my extension method in a delegate in the Razor WebGrid

查看:142
本文介绍了为什么我不能用我的扩展方法在剃刀的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屋!

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