C#中Activator.CreateInstance()方法用法分析
本文實例講述了C#中Activator.CreateInstance()方法用法。分享給大家供大家參考。具體分析如下:
Activator 類
包含特定的方法,用以在本地或從遠程創(chuàng)建對象類型,或獲取對現(xiàn)有遠程對象的引用。
C#在類工廠中動態(tài)創(chuàng)建類的實例,所使用的方法為:
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)使用到外部應用的DLL中類的實例,則此時需要進行反編譯操作,使用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è)計有所幫助。
相關(guān)文章
C#正則表達式分解和轉(zhuǎn)換IP地址實例(C#正則表達式大全 c#正則表達式語法)
這是我發(fā)了不少時間整理的C#的正則表達式,新手朋友注意一定要手冊一下哦,這樣可以節(jié)省很多寫代碼的時間。下面進行了簡單總結(jié)2013-12-12
C#字符串數(shù)組轉(zhuǎn)換為整形數(shù)組的方法
這篇文章主要介紹了C#字符串數(shù)組轉(zhuǎn)換為整形數(shù)組的方法,涉及C#數(shù)組遍歷與轉(zhuǎn)換的相關(guān)技巧,需要的朋友可以參考下2015-06-06

