转载:http://www.cnblogs.com/lcyhjx/p/7444179.html

动态实例化一个类,比较常见,代码如下

c# 动态实例化一个泛型类
namespace ConsoleApp2
{
    public class MyClass
    {

    }
}
c# 动态实例化一个泛型类
Type classType = Type.GetType("ConsoleApp2.MyClass, AssemblyName");
var instance =  Activator.CreateInstance(classType);

那如果这个类是泛型类,该如何实例化呢?  这里主要是要传递泛型参数

c# 动态实例化一个泛型类
namespace ConsoleApp2
{
    public class MyGenericClass<T>
    {

    }
}
c# 动态实例化一个泛型类
Type classType = Type.GetType("ConsoleApp2.MyGenericClass`1, AssemblyName");
Type constructedType = classType.MakeGenericType(typeof(T));
var instance = Activator.CreateInstance(constructedType);

 

相关文章:

  • 2021-10-25
  • 2021-06-07
  • 2021-10-26
  • 2021-10-11
  • 2022-12-23
  • 2021-09-05
猜你喜欢
  • 2022-12-23
  • 2021-06-09
  • 2021-05-29
  • 2022-01-10
  • 2022-12-23
相关资源
相似解决方案