开发者

Why does the WebGrid use dynamic in formatting?

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 c开发者_如何学Contravariant on T, but I'm confused about how covariance and contravariance work with dynamic.)


As far as the type system is concerned, dynamic is the same as object.

They cannot use a strongly-typed delegate because they don't have a strongly-typed value to pass.

Inside WebGrid, they get an Object from a PropertyDescriptor, and pass that to your delegate.

Covariance won't help here; had Func<YourType, string> been convertible to Func<object, string>, it would be possible to call it with any other type and get an invalid cast.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜