如何从这种通用情况中获取类型?
我试图编写一个泛型基类,它允许子类传递一个接口作为类型,然后让基类在泛型上调用方法,但我不知道如何做到这一点......
public class BaseController<T> : Controller where T : IPageModel
{
public virtual ActionResult Index()
{
IPageModel model = new T.GetType();
return View(model);
}
}
这不能编译,在仿制药方面我是否搞错了?
Im trying to write a generic base class that will allow sub classes to pass up an interface as the type and then have the baseclass call methods on the generic but I cant't work out how to do it...
public class BaseController<T> : Controller where T : IPageModel
{
public virtual ActionResult Index()
{
IPageModel model = new T.GetType();
return View(model);
}
}
That doesn't compile, have I got the wrong end of the stick when it comes to generics?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想你想要:
注意
T
上的new()
约束。 (有关详细信息,请参阅有关通用约束的 MSDN。)如果您确实需要与
T
相对应的Type
引用,您可以使用typeof(T)
- 但我不认为在这种情况下你需要它。I think you want:
Note the
new()
constraint onT
. (See MSDN on generic constraints for more information.)If you did need the
Type
reference corresponding toT
, you'd usetypeof(T)
- but I don't think you need it in this case.您应该执行以下操作才能启用创建实例:
You should do as bellow to enable creating instance: