动态传入泛型类

有这样的场景,对于泛型参数T需要在运行时传入,如下面的T

public class AnimalContext<T>
{
    public DoAnimalStuff()
    {
        //AnimalType Specific Code
    }
}

用一般方式是不可行的,因为T是在编译时确定的。

可以用反射来实现。

var type = typeof(AnimalContext<>).MakeGenericType(typeA.GetType());
var typeA_Context = Activator.CreateInstance(type);

猜你喜欢

转载自www.cnblogs.com/luhe/p/9259918.html