2012-11-29 299 views
3

我想在运行时编译和运行代码。我正在使用下面的代码来实现这一点。但是,当我试图调用该方法时,只需“查找源文件”浏览器对话框打开,代码就不会运行。任何人都可以在这里帮我。在运行时编译运行代码

Dim VBP As New VBCodeProvider 
Dim CVB As System.CodeDom.Compiler.ICodeCompiler 

CVB = VBP.CreateCompiler 
Dim PM As New System.CodeDom.Compiler.CompilerParameters 

PM.GenerateInMemory = True 
PM.GenerateExecutable = True 
PM.OutputAssembly = "RunCode.dll" 
PM.MainClass = "MainClass" 
PM.IncludeDebugInformation = True 

Dim ASM As System.Reflection.Assembly 
For Each ASM In AppDomain.CurrentDomain.GetAssemblies 
    PM.ReferencedAssemblies.Add(ASM.Location) 
Next 
Dim CompileResults As System.CodeDom.Compiler.CompilerResults 

CompileResults = CVB.CompileAssemblyFromSource(PM, sCode) 

Dim CompileErrors As System.CodeDom.Compiler.CompilerError 

For Each CompileErrors In CompileResults.Errors 
    RTMainScript.AppendText(vbCrLf & CompileErrors.ErrorNumber & ": " & CompileErrors.ErrorText & ", " & CompileErrors.Line) 
Next 

Dim objRun As New Object 
Dim vArgs() As Object 

objRun = CompileResults.CompiledAssembly.CreateInstance("RunCode.MainClass", False, BindingFlags.CreateInstance, Nothing, vArgs, Nothing, Nothing) 
If Not objRun Is Nothing Then 
    Dim oMethodInfo As MethodInfo = objRun.GetType().GetMethod("Main") 
    Dim oRetObj As Object = oMethodInfo.Invoke(objRun, BindingFlags.Static Or BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.NonPublic, Nothing, Nothing, Nothing) 'Find source dialog appears here 
Else 
    MsgBox("Compile Error") 
End If 
+0

我无法使用您的代码重现此错误。也许有写入它生成的临时DLL文件的权限问题。 – Griffin

回答

0

您提供的代码不完整。您正在使用此方法编译代码:

CompileResults = CVB.CompileAssemblyFromSource(PM, sCode) 

但是您实际上从未指定过什么sCode。如果你正在打开一个文件浏览器对话框,那么我很确定你的sCode是它的原因。在计算变量值以打开文件时,它必须设置在某个地方。

如果您尝试更改用于从文件编译的代码段,则将方法从CompileAssemblyFromFile()更改为CompileAssemblyFromSource()是不够的。您需要深入研究代码并更改所有相关方法。

0

确保您的线程模型是STA。

如果线程模型设置为MTA,则OpenFileDialog和类似对象将无法正常运行。 如果您因其他原因必须使用MTA,则可以创建自己的自定义OpenFileDialog类;有点糟糕。