2012-08-08 209 views
3

我正在尝试使用VBCodeProvider类的飞行代码编译。我想要做的是在代码中修改我的程序集中的公共变量。'TestString'未被声明。由于其保护级别,它可能无法访问。 (BC30451)

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

回答

3

就像正常的VB.NET,以及添加引用,你必须Imports相关的命名空间,或完全指定它。 (你已经编辑了这个问题,现在包括这个。)

在VS2008中插入你的代码到一个新的控制台项目(因为这是我打开的)并调整我的程序集名称后,我看到了和你一样的东西。

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

+0

感谢您的协助 – 2012-08-09 12:14:01

相关问题