詳細(xì)分析VB.NET動(dòng)態(tài)代碼
學(xué)習(xí)VB.NET時(shí),經(jīng)常會(huì)遇到使用VB.NET動(dòng)態(tài)代碼問(wèn)題,這里將介紹使用VB.NET動(dòng)態(tài)代碼問(wèn)題的解決方法,在這里拿出來(lái)和大家分享一下。
使用VB.NET動(dòng)態(tài)代碼
在運(yùn)行時(shí)創(chuàng)建一個(gè)控件是在無(wú)法確定應(yīng)用程序功能的時(shí)候采取的一種策略。但是動(dòng)態(tài)創(chuàng)建控件并不適用于所有的情況。有些時(shí)候你必須建立可執(zhí)行代碼,雖然你的應(yīng)用程序運(yùn)行的目的是補(bǔ)償不同極其之間的配置,不同用戶(hù)的需求,不同的環(huán)境需求或是其他要求。當(dāng)應(yīng)用程序所運(yùn)行的電腦不存在控件,那么通常是需要?jiǎng)?chuàng)建VB.NET動(dòng)態(tài)代碼的。
幸運(yùn)的是,.NET為我們提供了一系列VB.NET動(dòng)態(tài)代碼選項(xiàng)。例如,你可以創(chuàng)建一個(gè)可執(zhí)行的能獨(dú)立運(yùn)行的程序或是可以想運(yùn)行中的程序加載一個(gè)DLL然后再執(zhí)行。當(dāng)你需要演示一個(gè)外部任務(wù)的時(shí)候可以使用選擇可執(zhí)行,如運(yùn)行一種腳本——該DLL選項(xiàng)最適合擴(kuò)大現(xiàn)有的應(yīng)用程序功能。
你可以運(yùn)行來(lái)自文件或內(nèi)存的VB.NET動(dòng)態(tài)代碼。當(dāng)你需要不止一次地運(yùn)行代碼時(shí),可以使用文件。對(duì)代碼的檢查可以再次運(yùn)行外部文件而不需要對(duì)其進(jìn)行二次編譯。當(dāng)你需要多次演示任務(wù)的時(shí)候,如一個(gè)安裝請(qǐng)求,那可以使用內(nèi)存圖像。
當(dāng)然我們也可以更改源代碼。例如,你可以使用字符串來(lái)建立需要在應(yīng)用程序中直接使用的代碼。如果你需要代碼具有高度靈活性,且代碼本身不是很長(zhǎng)時(shí),這一方法的優(yōu)勢(shì)就非常顯著。也可以從文件里建立代碼,就如同VS一樣。這一方法最適用于相對(duì)穩(wěn)定且不需要復(fù)雜編碼的需求。第三種選擇是使用 Documentation Object Model來(lái)創(chuàng)建代碼并將其作為CodeDom樹(shù)型結(jié)構(gòu)的一個(gè)系列。該樹(shù)型結(jié)構(gòu)包括了CodeCormpileUnits.這就像是用DOM模式創(chuàng)建了一個(gè)XML文件。
使用動(dòng)態(tài)創(chuàng)建代碼的***方式是用示例來(lái)檢查一下。例三展示了一個(gè)基本“Hello World”示例。該示例用源代碼直接創(chuàng)建了代碼因此你可以看到整個(gè)運(yùn)行以及生成一個(gè)外部可執(zhí)行文件的過(guò)程。
- Private Sub btnTest3_Click() Handles btnTest3.Click
- ' Create a compiler.
- Dim Comp As VBCodeProvider = New VBCodeProvider()
- ' Define the parameters for the code you want to compile.
- Dim Parms As CompilerParameters = New CompilerParameters)
- ' We do want to create an executable, rather than a DLL.
- Parms.GenerateExecutable = True
- ' The compiler will create an output assembly called Output.
- Parms.OutputAssembly = "Output"
- ' The compiler won't treat warnings as errors.
- Parms.TreatWarningsAsErrors = False
- ' Add any assembly you want to reference.
- Parms.ReferencedAssemblies.Add("System.Windows.Forms.dll")
- ' Define the code you want to run.
- Dim SampleCode As StringBuilder = New StringBuilder()
- SampleCode.Append("Imports System.Windows.Forms" + vbCrLf)
- SampleCode.Append("Module TestAssembly" + vbCrLf)
- SampleCode.Append("Sub Main()" + vbCrLf)
- SampleCode.Append("MessageBox.Show(" + Chr(34) + _
- "Dynamically Created Code!" + _Chr(34) + ")" + vbCrLf)
- SampleCode.Append("End Sub" + vbCrLf)
- SampleCode.Append("End Module" + vbCrLf)
- ' Define the code to run.
- Dim Executable As CompilerResults = _
- Comp.CompileAssemblyFromSource(Parms, SampleCode.ToString())
- ' Display error messages if there are any.
- If Executable.Errors.HasErrors Then
- For Each Item As CompilerError In Executable.Errors
- MessageBox.Show(Item.ErrorText)
- Next
- Else
- ' If there aren't any error messages, start the
- ' executable.
- Process.Start("Output")
- End If
- End Sub
【編輯推薦】