本文實例講述了C#中Activator.CreateInstance()方法用法。
Activator 類
包含特定的方法,用以在本地或從遠程創建對象類型,或獲取對現有遠程對象的引用。
C#在類工廠中動態創建類的實例,所使用的方法為:
1. Activator.CreateInstance (Type) 2. Activator.CreateInstance (Type, Object[])
兩種方法區別僅為:創建無參數的構造方法和創建有參數的構造函數。
//System.Type.GetType(命名空間.類名,程序集) string vFullClassName = "Kernel.SimpleLibrary.Person,Kernel.SimpleLibrary"; Type.GetType("Kernel.SimpleLibrary.Person,Kernel.SimpleLibrary") //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);