首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将导入的名称空间馈送到CompileAssemblyFromSource

如何将导入的名称空间馈送到CompileAssemblyFromSource
EN

Stack Overflow用户
提问于 2012-10-04 07:03:21
回答 2查看 650关注 0票数 2

我正在尝试将VB源文件加载到内存中。但是,VB文件假定它所关联的Project在项目级别定义了一些全局“导入的命名空间”。此VB功能允许单个文件省略每个文件上的Imports语句(在C#中使用)。

代码语言:javascript
复制
    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框架。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-11-01 11:55:27

好吧,没有答案:(我猜框架没有做我想做的事情。下面是我使用Regex注入Imports语句的解决方案。

代码语言:javascript
复制
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语句的下面。

票数 1
EN

Stack Overflow用户

发布于 2016-06-09 23:27:53

可以使用CompilerParameters类的CompilerOptions属性导入命名空间。将这一行添加到示例中,编译器将不再生成编译器错误:

代码语言:javascript
复制
params.CompilerOptions = "/import:System.Data"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12718110

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档