看了網(wǎng)上很多關于dotnet動態(tài)創(chuàng)建類的實例的文章,我這里想總結一下,其實方法很簡單,就是用“activator.createinstance”。但是這個方法需要待創(chuàng)建的類的type作為參數(shù),為了獲得該參數(shù),可以利用[assembly].gettype方法,這個方法只需要待創(chuàng)建的類的名稱(名稱字符串)就可以了,最后的問題就是要獲得這個類所在的程序集。如何獲得待創(chuàng)建的類所在程序集,那么就解決了這個問題。
大家可以參考http://www.cnblogs.com/shadowk/archive/2006/11/14/560131.html,費了很多筆墨寫了一個比較完整的動態(tài)構造類的設計器。其實,在獲得程序集這個問題上,可以有更簡單的辦法,以下是我的做法。
利用microsoft.visualbasic.vbcodeprovider(),如果是c#可以用csharpcodeprovider(),將類文件編譯成為dll文件,然后利用[assembly].loadfrom("dll 的絕對路徑")加載該dll。這樣我們可以避免在那些創(chuàng)建dll和type的復雜代碼。我告訴我的項目組成員這個例子后,強調要打開思路,simple is perfect,凡事都盡量找簡便的方法來實現(xiàn),客戶永遠不會為我們那些復雜的代碼多花一分錢。
1.執(zhí)行編譯任務的方法:
public shared function compileexecutable()function compileexecutable(byval sourcename as string, byval dllpath as string, byref returndllname as string) as boolean
dim sourcefile as fileinfo = new fileinfo(sourcename)
dim provider as codedomprovider = nothing
dim compileok as boolean = false
' 根據(jù)原文件的擴展名選擇code provider
if sourcefile.extension.toupper(cultureinfo.invariantculture) = ".cs" then
provider = new microsoft.csharp.csharpcodeprovider()
elseif sourcefile.extension.toupper(cultureinfo.invariantculture) = ".vb" then
provider = new microsoft.visualbasic.vbcodeprovider()
else
console.writeline("原文件必須包含 .cs 或 .vb 擴展名")
end if
if not provider is nothing then
' 構造dll文件的全路徑
dim dllname as string = string.format("{0}/{1}.dll", _
dllpath, _
sourcefile.name.replace(".", "_"))
returndllname = dllname
dim cp as compilerparameters = new compilerparameters()
' 設置編譯控制參數(shù)
cp.generateexecutable = false '生成dll,如果是true則生成exe文件
cp.outputassembly = dllname
cp.generateinmemory = false
cp.treatwarningsaserrors = false
' 調用編譯方法將原代碼文件編譯成dll
dim cr as compilerresults = provider.compileassemblyfromfile(cp, _
sourcename)
if cr.errors.count > 0 then
' 顯示編譯錯誤
console.writeline("編譯錯誤 {0} 編譯成 {1}", _
sourcename, cr.pathtoassembly)
dim ce as compilererror
for each ce in cr.errors
console.writeline(" {0}", ce.tostring())
console.writeline()
next ce
else
' 顯示編譯成功的消息
console.writeline("原文件 {0} 編譯成 {1} 成功完成.", _
sourcename, cr.pathtoassembly)
end if
' 返回編譯結果
if cr.errors.count > 0 then
compileok = false
else
compileok = true
end if
end if
return compileok
end function
2.編譯dll,并動態(tài)創(chuàng)建類的實例。(這里類的原文件是class1.vb文件,放在website的app_code文件夾中了,實際使用時可以放在任意物理位置。)
dim strsourcefilename as string = server.mappath("~/app_code/class1.vb") '類文件的全路徑
dim strdllpath as string = server.mappath("~/app_code") '編譯后的dll文件存放的位置
dim strdllname as string = "" 'dll的全路徑(返回值)
compileexecutable(strsourcefilename, strdllpath, strdllname) '編譯原文件為dll文件
dim a as [assembly] = [assembly].loadfrom(strdllname) '加載dll
dim mytype as system.type = a.gettype("class1") '獲得class1的type
dim obj as object = activator.createinstance(mytype) '獲得class1的實例
3.class1.vb原文件
public class class1class class1
public i as integer
end class
新聞熱點
疑難解答
圖片精選