C#中Activator.CreateInstance()方法用法分析


本文實例講述了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);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM