如何从这种通用情况中获取类型?

Exi*_*tos 3 c# generics

我试图写一个通用的基类,允许子类作为类型传递一个接口,然后在泛型上有基类调用方法,但我不知道怎么做...

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

        return View(model);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*eet 6

我想你想要:

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

注意new()约束T.(有关更多信息,请参阅有关通用约束的MSDN.)

如果你确实需要Type相应的参考T,你会使用typeof(T)- 但在这种情况下我认为你不需要它.