我正在尝试使用VBCodeProvider
该类进行一些即时代码编译。我想要做的是在代码中修改我的程序集中的公共变量。
我的应用程序中有一个Public TestString As String = ""
。
这是我用来编译的代码:
Dim codeProvider As New VBCodeProvider()
Dim optParams As New CompilerParameters
optParams.ReferencedAssemblies.Add("MyAssembly.exe")
optParams.ReferencedAssemblies.Add("system.windows.forms.dll")
optParams.CompilerOptions = "/t:library"
optParams.GenerateInMemory = True
Dim results As CompilerResults = codeProvider.CompileAssemblyFromSource(optParams, RichTextBox1.Text)
If results.Errors.Count > 0 Then
Dim sb As New StringBuilder("Compilation Failed with the following error(s)" + CR_LF + CR_LF)
For Each CompErr As CompilerError In results.Errors
sb.Append(String.Format("Line {0} - {1} ({2}){3}", CompErr.Line, CompErr.ErrorText, CompErr.ErrorNumber, CR_LF))
Next
MessageBox.Show(sb.ToString, "Compile Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Dim assy As System.Reflection.Assembly = results.CompiledAssembly
Dim exeinstance As Object = assy.CreateInstance("Script")
Dim typ As Type = exeinstance.GetType
Dim method As MethodInfo = typ.GetMethod("Main")
method.Invoke(exeinstance, Nothing)
End If
这是我的文本框中的代码:
Imports System
Imports MyAssembly
Class Script
Sub Main()
TestString="foo"' <-- This line fails compilation
End Sub
End Class
我得到的错误是未声明“TestString”。由于其保护级别,它可能无法访问。(BC30451)