在VB.NET中实现代码动态编译
通过.NET的编译系统,可以实现非常复杂的功能,比如动态算法,EXE(DLL)反向生成VB代码之类的
今天很累了,先把我的代码贴上来
如果大家有兴趣,我会考虑写一个专题文章
建立一个窗体
添加一个Textbox,叫做Textbox1
然后在里面输入如下文本
'---剪切线---------------
imports Microsoft.VisualBasic
Public Module Hello
Public Function SayHello()
MsgBox("TEST")
End Function
End Module
'------------------
添加一个CommandButtion,叫做Button1
然后,使用如下源代码
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myDC As New DynamicCompile
myDC.CompileVB(TextBox1.Text)
End Sub
然后,把下面的代码放到一个Class里面
'------剪切线-----------
Imports System.CodeDom
Imports System.CodeDom.Compiler
Imports System.Reflection
Public Class DynamicCompile
Public Sub CompileVB(ByVal Code As String)
Dim myProvider As New Microsoft.VisualBasic.VBCodeProvider
Dim Compailer As ICodeCompiler = myProvider.CreateCompiler
Dim CompailerParamentes As New CompilerParameters
Dim myAssembly As [Assembly]
Dim mySub As System.Reflection.MethodInfo
Dim MyClass1 As System.Type
With CompailerParamentes
.ReferencedAssemblies.Add("C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Microsoft.VisualBasic.dll")
.ReferencedAssemblies.Add("C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\mscorlib.dll")
'.OutputAssembly = "temp.dll"
.GenerateInMemory = True
End With
myAssembly = Compailer.CompileAssemblyFromSource(CompailerParamentes, Code).CompiledAssembly
MyClass1 = myAssembly.GetType("Hello")
mySub = MyClass1.GetMethod("SayHello")
mySub.Invoke(MyClass1, Nothing)
End Sub
End Class
'-----------------
完成了,试试看吧
测试环境 :VS.NET 2003+Winxp(sp1)+.NET Framework 1.1