[英]DisplayNameFor for interface deriving from IEnumerable<T>
当我将IEnumerable<T>
声明为视图模型时, HtmlHelper<T>.DisplayNameFor()
可以正常工作,从而为实际的类型化模型提供了智能支持。
@model IEnumerable<MyModel>
// e.g. for <th>
@Html.DisplayNameFor(model => model.Id)
但是,当我声明自IEnumerable<T>
派生的自定义类型时,它突然停止工作。
@model IPagedList<MyModel>
@Html.DisplayNameFor(model => model.Id) // Cannot resolve symbol 'Id'
而IPagedList<T>
为:
public interface IPagedList<T> : IEnumerable<T> {}
有什么办法解决这个问题?
这就是C#中重载解析的工作方式。 特定
public static void DoSomething<T>(T t)
{ }
public static void DoSomething<T>(IEnumerable<T> t)
{ }
然后DoSomething(new int[0])
将调用T
与过载T = int[]
而不是IEnumerable<T>
具有过载T = int
。
这是因为,“转化率”从int[]
到T
是在前者的情况下“更好”(其中, T = int[]
比从转换int[]
到IEnumerable<T>
在后者的情况下(其中, T = int
) (请参见7.5.3.2 Better function member
和7.5.3.3 7.5.3.3 Better conversion from expression
C#规范中的7.5.3.3 7.5.3.3 Better conversion from expression
。)
我认为您现在唯一的选择是使用.First()
来指定您正在访问模型的元素:
@Html.DisplayNameFor(model => model.First().Id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.