如何访问ViewUserControl在运行时期望的类型?

时间:2010-10-04 16:35:44

标签: c# asp.net-mvc

如果你有:

 System.Web.Mvc.ViewUserControl<T>

如何在运行时访问T?

我有一个我传入的基类

Html.RenderPartial("ViewName", BaseControlModel);

但我想创建另一种扩展方法,例如

Html.RenderTypedPartial("ViewName", BaseControlModel);

这样在ViewName.ascx的上下文中,我的BaseControlModel从原始声明转换为类型T.我已经有了将BaseControlModel转换为我期望的类型的代码,它看起来像这样:

BaseControlModel.GetModel<T>();

但我想在RenderTypedPartial中一般调用它,而不是在我的视图中专门请求类型T.

10/5更新: 我继续从CodePlex上的源代码将粘贴的RenderPartial和FindPartialView复制到我自己的扩展方法中,我为IView引用得到的类型是一个WebFormView,它没有我在部分.ascx中定义的泛型参数类型...

1 个答案:

答案 0 :(得分:0)

obj.GetType().GetGenericArguments()[0];

Type本身有GetGenericArguments来提取这个,你也可以通过MakeGenericType创建泛型类型。

http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx

编辑:您可以构建类似的类型:

var type = typeof(ViewUserControl<>).MakeGenericType(..);
return Activator.CreateInstance(type, new object[] { }); //object[] is ctor parms