.net - 'TestString' 未声明。由于其保护级别,它可能无法访问。 (BC30451)

标签 .net vb.net scripting vbcodeprovider

<分区>

我正在尝试使用 VBCodeProvider 类进行一些动态代码编译。我希望能够做的是在代码中修改程序集中的公共(public)变量。

我的应用程序中有一个 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' is not declared。由于其保护级别,它可能无法访问。 (BC30451)

最佳答案

就像普通的 VB.NET 一样,除了添加引用外,您还必须 Imports 相关命名空间,或完全指定它。 (您已编辑问题以包含此内容。)

将您的代码插入 VS2008 中的新控制台项目(因为这是我打开的)并调整我的程序集名称后,我看到了与您相同的结果。

我通过将 Public 添加到默认的 Module Module1 来修复它。

关于.net - 'TestString' 未声明。由于其保护级别,它可能无法访问。 (BC30451),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11860742/

相关文章:

asp.net - 格式化此日期时间,不带秒或 AM/PM

linux - 字符串 Bash 脚本 if then 语句失败

powershell - if-else 不在 powershell 脚本中执行

c# - 在映射中保留 null - 不要为类型创建默认值

c# - 串行端口 Port.Write() 命令

.net - 使用 clickonce 部署时不要覆盖 app.config

.net - CAML 查询比较 DateTime 与 Eq

c# - 如何在 .net 4.5 中读取连接字符串

vb.net - 您的许可证在差异工具中无效

windows - 将脚本作为字符串传递给 cscript/wscript