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