为什么 WebGrid 使用动态格式?
我正在 ASP.NET MVC 3 Razor 项目中使用 System.Web.Helpers.WebGrid
,但我无法理解为什么 WebGridColumn
的格式参数> 是一个Func<动态,对象>
。
如果我创建这样的列...
grid.Column(
format: x => string.Format("{0:d}", x.StartDate)
);
...我不会在 StartDate 属性上得到强类型。如果我尝试像这样绕过它...
grid.Column(
format: (MyObjectType x) => string.Format("{0:d}", x.StartDate)
);
...我在运行时被告知我的 lambda 无法转换为 Func
。有什么方法可以在这里使用非动态 lambda 吗?即使它只是 ?
(我在 .NET 4.0 中,Func
应该是 T 上的逆变,但我对协变和逆变如何与动态一起工作感到困惑。)
I'm working with the System.Web.Helpers.WebGrid
in an ASP.NET MVC 3 Razor project, and I'm having trouble understanding why the format parameter for a WebGridColumn
is a Func<dynamic, object>
.
If I create a column like this...
grid.Column(
format: x => string.Format("{0:d}", x.StartDate)
);
...I don't get strong typing on the StartDate property. If I try to get around it like this...
grid.Column(
format: (MyObjectType x) => string.Format("{0:d}", x.StartDate)
);
...I'm told at runtime that my lambda can't be cast to a Func<dynamic, object>
. Is there some way I can use a non-dynamic lambda here? Even if it's just <object, object>
?
(I'm in .NET 4.0, and Func<in T, out TResult>
is supposed to be contravariant on T, but I'm confused about how covariance and contravariance work with dynamic.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
就类型系统而言,
dynamic
与object
相同。它们无法使用强类型委托,因为它们没有要传递的强类型值。
在
WebGrid
内,它们从PropertyDescriptor
获取一个Object
,并将其传递给您的委托。协方差在这里没有帮助;如果
Func
可转换为Func
,则可以使用任何其他类型调用它并获得无效的强制转换。As far as the type system is concerned,
dynamic
is the same asobject
.They cannot use a strongly-typed delegate because they don't have a strongly-typed value to pass.
Inside
WebGrid
, they get anObject
from aPropertyDescriptor
, and pass that to your delegate.Covariance won't help here; had
Func<YourType, string>
been convertible toFunc<object, string>
, it would be possible to call it with any other type and get an invalid cast.