【发布时间】:2013-07-03 05:33:33
【问题描述】:
我正在尝试编写一个通用的(意味着在许多地方都很有用)控件,我可以在整个公司中重复使用它。
我的视图和视图模型中的实际 C# 泛型存在问题。
这是我正在尝试做的一个示例:
通用局部视图:(_Control.cshtml)
@model SimpleExample<dynamic>
@Model.HtmlTemplate(Model.Data)
查看数据:(SimpleExample.cs)
public class SimpleExample<T>
{
public T Data;
public Func<T, System.Web.WebPages.HelperResult> HtmlTemplate;
}
用法示例:(FullView.cshtml)
@model Foo.MyViewData
@Html.Partial("_Control", new SimpleExample<MyViewData>
{
Data = Model,
HtmlTemplate = @<div>@item.SomeProperty</div>
})
我正在寻找的功能的重要部分是消费者在编写其 Html 内联时获得一个类型化的对象,以便他们可以使用 Intellisense(如FullView.cshtml)。
一切编译正常,智能感知工作正常,但运行时出现错误:
The model item passed into the dictionary is of type
'AnytimeHealth.Web.ViewData.SimpleExample`1[Foo.MyViewData]',
but this dictionary requires a model item of type
'AnytimeHealth.Web.ViewData.SimpleExample`1[System.Object]'.
我读到我可能可以在我的泛型类型上使用协方差来使其工作,但我不知道该怎么做。
能否请您指导我如何使其正常工作?
【问题讨论】:
标签: c# asp.net-mvc-3 generics razor