从文本 VB.NET 导入代码 [英] Import code from text VB.NET
问题描述
是否可以将文本作为代码导入,然后将其添加到 vb.net 的子文件中?如果我有一个填充了代码的 .txt 文件,我可以以编程方式(通过按钮)导入它吗?
Is it event possible to import text as code, then add it in a sub in vb.net? If I have a .txt file filled with code can I import it programatically (by a button)?
我需要的是让 vb.net 接受该脚本(txt 文件),并使用它来声明变量并创建函数/子 - 这就是我所需要的.
What I need is to make vb.net to accept that script (txt file), and use it to declare variables and make functions/subs - that's all I need to.
推荐答案
您可以使用 CodeDom 对象执行此类操作.CodeDom 对象允许您在运行时动态生成程序集.例如,如果你制作一个界面
You can do this kind of thing using the CodeDom objects. The CodeDom objects allow you to dynamically generate assemblies at run-time. For instance, if you make an interface
Public Interface IScript
Property Variable1 As String
Sub DoWork()
End Interface
然后,您创建一个方法,如下所示:
Then, you create a method, like this:
Imports Microsoft.VisualBasic
Imports System.CodeDom.Compiler
' ...
Public Function GenerateScript(code As String) As IScript
Using provider As New VBCodeProvider()
Dim parameters As New CompilerParameters()
parameters.GenerateInMemory = True
parameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location)
Dim interfaceNamespace As String = GetType(IScript).Namespace
Dim codeArray() As String = New String() {"Imports " & interfaceNamespace & Environment.NewLine & code}
Dim results As CompilerResults = provider.CompileAssemblyFromSource(parameters, codeArray)
If results.Errors.HasErrors Then
Throw New Exception("Failed to compile script")
Else
Return CType(results.CompiledAssembly.CreateInstance("Script"), IScript)
End If
End Using
End Function
现在,您可以这样称呼它:
Now, you can call it like this:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim builder As New StringBuilder()
builder.AppendLine("Public Class Script")
builder.AppendLine(" Implements IScript")
builder.AppendLine(" Public Property Variable1 As String Implements IScript.Variable1")
builder.AppendLine(" Public Sub DoWork() Implements IScript.DoWork")
builder.AppendLine(" Variable1 = ""Hello World""")
builder.AppendLine(" End Sub")
builder.AppendLine("End Class")
Dim script As IScript = GenerateScript(builder.ToString())
script.DoWork()
MessageBox.Show(script.Variable1) ' Displays "Hello World"
End Sub
显然,您可以从文本文件中加载代码,而不是在字符串生成器中构建代码,如下所示:
Obviously, instead of building the code in a string builder, you could load it out of a text file, like this:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim script As IScript = GenerateScript(File.ReadAllText("C:\script.txt")
script.DoWork()
MessageBox.Show(script.Variable1) ' Displays "Hello World"
End Sub
这篇关于从文本 VB.NET 导入代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!