我正在尝试将VB源文件加载到内存中。但是,VB文件假定它所关联的Project在项目级别定义了一些全局“导入的命名空间”。此VB功能允许单个文件省略每个文件上的Imports语句(在C#中使用)。
Dim sourceCode As String = ""
'sourceCode &= "Imports System.Data" & vbNewLine
sourceCode &= "Class Foo" & vbNewLine
sourceCode &= "Sub Print()" & vbNewLine
sourceCode &= "Dim dtbl As DataTable" & vbNewLine
sourceCode &= "System.Console.WriteLine(""Hello, world!"")" & vbNewLine
sourceCode &= "End Sub" & vbNewLine
sourceCode &= "End Class" & vbNewLine
Dim compiler As New Microsoft.VisualBasic.VBCodeProvider
Dim params As New Compiler.CompilerParameters
params.ReferencedAssemblies.Add("System.dll")
params.ReferencedAssemblies.Add("System.Data.dll")
params.ReferencedAssemblies.Add("System.Xml.dll")
params.GenerateInMemory = True
params.GenerateExecutable = False
Dim results As Compiler.CompilerResults = compiler.CompileAssemblyFromSource(params, sourceCode)
If results.Errors.Count > 0 Then
For Each compileError In results.Errors
Console.WriteLine(compileError.ToString)
Next
Return
End If
Dim assembly = results.CompiledAssembly第2行被注释掉。如果我取消注释,并添加Imports语句,代码就能正常工作。如果我将"Dim dtbl As DataTable“改为"Dim dtbl As System.Data.DataTable”,也可以正常工作。
除了不注释这行代码之外,有没有一种方法可以将此Imports语句提供给编译器或参数,就像它是全局项目级导入的命名空间一样?
我可以将这个Imports语句添加到我读入的每个文件的顶部。但是如果它已经存在,那么我会得到一个错误,即Imports语句是重复的。我可以做一些正则表达式检查,看看Imports语句是否已经存在,但我希望尽可能多地利用System.CodeDom框架。
发布于 2012-11-01 11:55:27
好吧,没有答案:(我猜框架没有做我想做的事情。下面是我使用Regex注入Imports语句的解决方案。
sourceCode = AddImportsIfNeeded(sourceCode, "System.Data")
Private Function AddImportsIfNeeded(ByVal sourceCode As String, ByVal namespaceToImport As String) As String
If Not Regex.IsMatch(sourceCode, "^\s*Imports\s+" & Regex.Escape(namespaceToImport) & "\s*$", RegexOptions.Multiline) Then
Return "Imports " & namespaceToImport & vbNewLine & sourceCode
End If
Return sourceCode
End Function请注意,如果文件包含Option语句(如Option Strict On),这将不起作用。Imports语句必须位于Option语句的下面。
发布于 2016-06-09 23:27:53
可以使用CompilerParameters类的CompilerOptions属性导入命名空间。将这一行添加到示例中,编译器将不再生成编译器错误:
params.CompilerOptions = "/import:System.Data"https://stackoverflow.com/questions/12718110
复制相似问题