简体   繁体   English

获取具体类型并创建接口类型参数的实例?

[英]Get a concrete type and create instance of interface type parameter?

Let say I the construcor, 假设我是construcor,

    public MyClass(Manager<Iinterface> manager)
    {
         // How can i get the type of Iinterface and then create an instance
    }

Is it possible that I can make this constructor generic? 我可以使此构造函数通用吗? like, 喜欢,

    public MyClass<T>(Manager<T> manager) where T is Iinterface
    {
         // How can i get the type of Iinterface and then create an instance
    }

You need to define this with the class itself, not the constructor. 您需要使用类本身而不是构造函数来定义它。 If you can't make the class itself generic, then static "Create" method could do this. 如果您不能使类本身具有通用性,则可以使用静态“创建”方法来实现。 But the, there is probably problem of passing the instance of Manager<T> to Manager<Iinterface> , because classes cannot be covariant. 但是,可能存在将Manager<T>的实例传递给Manager<Iinterface> ,因为类不能是协变的。

public class MyClass
{
    public MyClass(Manager<Iinterface> manager) 
    {
        // How can i get the type of Iinterface and then create an instance
    }
    public static MyClass Create<T>(Manager<T> manager) where T : Iinterface, new()
    {
        Type tType = typeof(T);
        T tInstance = new T();

        return new MyClass([some parameters]);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM