我正在尝试从文本文件中读取和编译代码。我已经完成了一些部分,但在尝试向窗体添加控件时感到困难。请指导我。我附上代码。
Public Class Form1
Sub Execute()
' Creates object of the compiler
Dim objCodeCompiler As System.CodeDom.Compiler.ICodeCompiler = New VBCodeProvider().CreateCompiler
'References/Parameters.
Dim objCompilerParameters As New System.CodeDom.Compiler.CompilerParameters()
objCompilerParameters.ReferencedAssemblies.Add("System.dll")
objCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll")
objCompilerParameters.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll")
'Compiles in memory.
objCompilerParameters.GenerateInMemory = True
'Runs the source code.
'You can use resources, textbox's or even the settings, up to you! :D
'Dim strCode As String = TextBox1.Text
'Compiler Results
'Dim objCompileResults As System.CodeDom.Compiler.CompilerResults = objCodeCompiler.CompileAssemblyFromSource(objCompilerParameters, strCode)
Dim objCompileResults As System.CodeDom.Compiler.CompilerResults = objCodeCompiler.CompileAssemblyFromFile(objCompilerParameters, "H:\VB project\LE21 - CodeDom - Run code from Textbox\LE21 - CodeDom - Run code from Textbox\LE21 - CodeDom - Run code from Textbox\file.txt")
'If an Error occurs
If objCompileResults.Errors.HasErrors Then
MsgBox("Error: Line>" & objCompileResults.Errors(0).Line.ToString & ", " & objCompileResults.Errors(0).ErrorText)
Exit Sub
End If
'Creates assembly
Dim objAssembly As System.Reflection.Assembly = objCompileResults.CompiledAssembly
Dim objTheClass As Object = objAssembly.CreateInstance("MainClass")
If objTheClass Is Nothing Then
MsgBox("Can't load class...")
Exit Sub
End If
'Trys to excute
Try
objTheClass.GetType.InvokeMember("ExecuteCode",
System.Reflection.BindingFlags.InvokeMethod, Nothing, objTheClass, Nothing)
Catch ex As Exception
MsgBox("Error:" & ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Runs the source code from textbox1.
Execute()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim p As New Form2
p.Text = "hahahahah"
p.Show()
End Sub
End Class
答案 0 :(得分:0)
"类型Form2未定义"
那是因为你还没有定义它。您可能正在动态加载和编译包含确定它的代码的某个文件。但编译器无法在编译时知道 。作为一个静态类型系统,编译器需要知道编译代码时所使用的所有类型。
如果您从文件动态加载类定义,则还需要动态调用这些类定义。这会涉及很多reflection和CodeDOM以及诸如此类的东西。它不会很漂亮,并且它肯定不会进行编译时类型检查。 (并且它将非常"字符串输入"在某种意义上,您不会创建Form2
的实例,而是要从反射中请求创建实例"Form2"
并且希望得到最好的。)所以你想要为诸如不存在的类之类的东西进行大量的错误处理。