C#在類工廠中動態創建類的實例,所使用的方法為:
1. Activator.CreateInstance (Type) 2. Activator.CreateInstance (Type, Object[]) |
兩種方法區別僅為:創建無參數的構造方法和創建有參數的構造函數。
//Activator.CreateInstance(Type)
object result = null;
Type typeofControl =null;
typeofControl = Type.GetType(vFullClassName);
result = Activator.CreateInstance(typeofControl);
//Activator.CreateInstance(Type,Object[])
object result = null;
Type typeofControl =null;
typeofControl = Type.GetType(vFullClassName);
result = Activator.CreateInstance(typeofControl, objParam);
但是在動態創建時,可能會動態使用到外部應用的DLL中類的實例,則此時需要進行反編譯操作,使用Reflection命名控件下的Assembly類。
//先使用Assembly類載入DLL,再根據類的全路徑獲取類
object result = null;
Type typeofControl = null;
Assembly tempAssembly;
tempAssembly = Assembly.LoadFrom(vDllName);
typeofControl = tempAssembly.GetType(vFullClassName);
result = Activator.CreateInstance(typeofControl, objParam);