C# 如何创建具有未知泛型类型参数的ASP.net MVC用户控件?
目前,我正在为一些客户模型类使用基类。定义如下C# 如何创建具有未知泛型类型参数的ASP.net MVC用户控件?,c#,.net,asp.net-mvc,generics,casting,C#,.net,Asp.net Mvc,Generics,Casting,目前,我正在为一些客户模型类使用基类。定义如下 public abstract class BaseCustomerModel<T> where T : IUserEntity 该属性以及其他内容将在ErrorTextControl.ascx中公开: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<(...).Models.BaseCustomerModel<(...).I
public abstract class BaseCustomerModel<T>
where T : IUserEntity
该属性以及其他内容将在ErrorTextControl.ascx中公开:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<(...).Models.BaseCustomerModel<(...).IUserEntity>>" %>
<tr>
<td colspan="2"><%: Html.DisplayFor(model => model.ErrorMessage) %></td>
</tr>
model.ErrorMessage)%%>
我将这样调用用户控件:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<(...).Models.MyUserModel>" %>
<% if (Model.HasErrors)
{
Html.RenderPartial("ErrorTextControl", Model);
} %>
最后一段代码(MyUserEntity实现IUserEntity):
公共类MyUserModel:BaseCustomerModel
不幸的是,这显然不起作用,因为泛型类型不能隐式地转换为IUSERENITY。因此,在浏览器中会出现以下错误消息:
异常详细信息:System.InvalidOperationException:传递到字典的模型项的类型为
“(…).Models.MyUserModel”,但此字典需要类型为的模型项
“(…).Models.BaseCustomerModel`1[(…).IUserEntity]”
因此,问题是:
- 有没有办法定义一个具有泛型基类的用户控件,该基类的类型还不知道?如果是,如何完成这样的事情
- 如果没有,是否有任何变通方法、通用解决方案或想法能够拥有通用用户控件
非常感谢。嗯,我自己刚刚想出了一个解决办法 只是BaseCustomerModel的一个额外接口:
public abstract class BaseCustomerModel<T> : IContainErrorMessage
where T : IUserEntity
公共抽象类BaseCustomerModel:IContainErrorMessage
T:我的宁静在哪里
这样,用户控件就不必担心泛型:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<(...).Models.IContainErrorMessage>" %>
您可以尝试以下方法:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
monty-您需要某种绑定的公共接口(除了IUserEntity)。你确认了这个吗??。我之所以这样说,是因为您将强键入属性集,因此这些属性将需要成为合同的一部分。如果只是IUserEntity部分需要暴露于ErrorTextControl.ascx,那么为什么不:-或者我完全没有抓住要点:)杰普,我也发现了自己。。。看到我贴的答案了吧。很好——你知道这很有道理!!;)好球!!当然应该是这样的:“Inherits=”System.Web.Mvc.ViewUserControl“,但不幸的是:编译器错误消息:CS0311:类型“dynamic”不能用作泛型类型或方法“(…).Models.BaseCustomerModel”中的类型参数“T”。没有从“dynamic”到“(…).IUserEntity”的隐式引用转换。
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<(...).Models.IContainErrorMessage>" %>
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>