动态传入泛型类

有这样的场景,对于泛型参数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);

 

posted on 2018-07-03 18:00  傍晚雨  阅读(466)  评论(0编辑  收藏  举报