C#中Activator.CreateInstance()方法用法分析
本文實(shí)例講述了C#中Activator.CreateInstance()方法用法。分享給大家供大家參考。具體分析如下:
Activator 類
包含特定的方法,用以在本地或從遠(yuǎn)程創(chuàng)建對象類型,或獲取對現(xiàn)有遠(yuǎn)程對象的引用。
C#在類工廠中動態(tài)創(chuàng)建類的實(shí)例,所使用的方法為:
1. Activator.CreateInstance (Type)
2. Activator.CreateInstance (Type, Object[])
兩種方法區(qū)別僅為:創(chuàng)建無參數(shù)的構(gòu)造方法和創(chuàng)建有參數(shù)的構(gòu)造函數(shù)。
//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);
但是在動態(tài)創(chuàng)建時,可能會動態(tài)使用到外部應(yīng)用的DLL中類的實(shí)例,則此時需要進(jìn)行反編譯操作,使用Reflection命名控件下的Assembly類。
//先使用Assembly類載入DLL,再根據(jù)類的全路徑獲取類 object result = null; Type typeofControl = null; Assembly tempAssembly; tempAssembly = Assembly.LoadFrom(vDllName); typeofControl = tempAssembly.GetType(vFullClassName); result = Activator.CreateInstance(typeofControl, objParam);
希望本文所述對大家的C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
C#正則表達(dá)式分解和轉(zhuǎn)換IP地址實(shí)例(C#正則表達(dá)式大全 c#正則表達(dá)式語法)
這是我發(fā)了不少時間整理的C#的正則表達(dá)式,新手朋友注意一定要手冊一下哦,這樣可以節(jié)省很多寫代碼的時間。下面進(jìn)行了簡單總結(jié)2013-12-12C#中實(shí)現(xiàn)抽象類里建立靜態(tài)方法
這篇文章主要介紹了C#中實(shí)現(xiàn)抽象類里建立靜態(tài)方法,需要的朋友可以參考下2014-07-07C#字符串?dāng)?shù)組轉(zhuǎn)換為整形數(shù)組的方法
這篇文章主要介紹了C#字符串?dāng)?shù)組轉(zhuǎn)換為整形數(shù)組的方法,涉及C#數(shù)組遍歷與轉(zhuǎn)換的相關(guān)技巧,需要的朋友可以參考下2015-06-06