標籤:style blog http io 使用 ar sp div art
本文來自:http://blog.csdn.net/jaydawson/article/details/5539438
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);
C# Activator.CreateInstance()方法使用