動態實例化一個類,比較常見,代碼以下spa
namespace ConsoleApp2 { public class MyClass { } }
Type classType = Type.GetType("ConsoleApp2.MyClass, AssemblyName"); var instance = Activator.CreateInstance(classType);
那若是這個類是泛型類,該如何實例化呢? 這裏主要是要傳遞泛型參數code
namespace ConsoleApp2 { public class MyGenericClass<T> { } }
Type classType = Type.GetType("ConsoleApp2.MyGenericClass`1, AssemblyName"); Type constructedType = classType.MakeGenericType(typeof(T)); var instance = Activator.CreateInstance(constructedType);