2011-11-05 79 views
3

我试图写一个通用的基类,这将允许子类传递一个接口作为类型,然后在泛型上有基类调用方法,但我不知道如何去做...如何从这种一般情况下获得类型?

public class BaseController<T> : Controller where T : IPageModel 
{ 
    public virtual ActionResult Index() 
    { 
     IPageModel model = new T.GetType(); 

     return View(model); 
    } 
} 

这不能编译,当涉及到泛型时,我得到了棒的错误结局吗?

回答

6

我想你想:

public class BaseController<T> : Controller where T : IPageModel, new() 
{ 
    public virtual ActionResult Index() 
    { 
     IPageModel model = new T(); 
     return View(model); 
    } 
} 

注意new()约束上T。 (更多信息请参见MSDN on generic constraints

如果没有需要对应TType参考,你会使用typeof(T) - 但我不认为你需要它在这种情况下。

+0

谢谢乔恩,是什么在年底新的位呢?在基类实例化时确保类型是'新建'? – Exitos

+1

@ Pete2k:不 - 这里没有继承。它只是要求'T'有一个无参数的构造函数。我会编辑一个链接到我的答案。 –

1

你应该做的波纹管,使创建实例:

public class BaseController<T> : Controller where T :IPageModel,new() 
{ 
    public virtual ActionResult Index() 
    { 
     IPageModel model = new T(); 

     return View(model); 
    } 

} 
相关问题