詳細(xì)分析VB.NET動態(tài)代碼
學(xué)習(xí)VB.NET時,經(jīng)常會遇到使用VB.NET動態(tài)代碼問題,這里將介紹使用VB.NET動態(tài)代碼問題的解決方法,在這里拿出來和大家分享一下。
使用VB.NET動態(tài)代碼
在運(yùn)行時創(chuàng)建一個控件是在無法確定應(yīng)用程序功能的時候采取的一種策略。但是動態(tài)創(chuàng)建控件并不適用于所有的情況。有些時候你必須建立可執(zhí)行代碼,雖然你的應(yīng)用程序運(yùn)行的目的是補(bǔ)償不同極其之間的配置,不同用戶的需求,不同的環(huán)境需求或是其他要求。當(dāng)應(yīng)用程序所運(yùn)行的電腦不存在控件,那么通常是需要創(chuàng)建VB.NET動態(tài)代碼的。
幸運(yùn)的是,.NET為我們提供了一系列VB.NET動態(tài)代碼選項(xiàng)。例如,你可以創(chuàng)建一個可執(zhí)行的能獨(dú)立運(yùn)行的程序或是可以想運(yùn)行中的程序加載一個DLL然后再執(zhí)行。當(dāng)你需要演示一個外部任務(wù)的時候可以使用選擇可執(zhí)行,如運(yùn)行一種腳本——該DLL選項(xiàng)最適合擴(kuò)大現(xiàn)有的應(yīng)用程序功能。
你可以運(yùn)行來自文件或內(nèi)存的VB.NET動態(tài)代碼。當(dāng)你需要不止一次地運(yùn)行代碼時,可以使用文件。對代碼的檢查可以再次運(yùn)行外部文件而不需要對其進(jìn)行二次編譯。當(dāng)你需要多次演示任務(wù)的時候,如一個安裝請求,那可以使用內(nèi)存圖像。
當(dāng)然我們也可以更改源代碼。例如,你可以使用字符串來建立需要在應(yīng)用程序中直接使用的代碼。如果你需要代碼具有高度靈活性,且代碼本身不是很長時,這一方法的優(yōu)勢就非常顯著。也可以從文件里建立代碼,就如同VS一樣。這一方法最適用于相對穩(wěn)定且不需要復(fù)雜編碼的需求。第三種選擇是使用 Documentation Object Model來創(chuàng)建代碼并將其作為CodeDom樹型結(jié)構(gòu)的一個系列。該樹型結(jié)構(gòu)包括了CodeCormpileUnits.這就像是用DOM模式創(chuàng)建了一個XML文件。
使用動態(tài)創(chuàng)建代碼的***方式是用示例來檢查一下。例三展示了一個基本“Hello World”示例。該示例用源代碼直接創(chuàng)建了代碼因此你可以看到整個運(yùn)行以及生成一個外部可執(zhí)行文件的過程。
- 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
【編輯推薦】