3

是否可以将文本作为代码导入,然后将其添加到 vb.net 的子目录中?如果我有一个充满代码的 .txt 文件,我可以通过编程方式(通过按钮)导入它吗?

我需要的是让 vb.net 接受该脚本(txt 文件),并使用它来声明变量并制作函数/子程序——这就是我所需要的。

4

1 回答 1

3

您可以使用 CodeDom 对象来做这种事情。CodeDom 对象允许您在运行时动态生成程序集。例如,如果你制作一个接口

Public Interface IScript
    Property Variable1 As String
    Sub DoWork()
End Interface

然后,您创建一个方法,如下所示:

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

现在,您可以这样称呼它:

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

显然,您可以从文本文件中加载代码,而不是在字符串生成器中构建代码,如下所示:

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
于 2013-02-05T15:33:17.640 回答