c# - Roslyn - CSharpCompilation

标签 c# roslyn

我正在使用 CSharpCompilation 类来编译 SyntaxTree,其中根是一个类声明。我向构造函数传递了一个包含我的 using 语句的 CSharpCompilationOptions 对象。

我的理解是语法树将使用我通过的任何 using 语句的上下文进行编译。但是,当尝试访问在我传递给选项对象的“使用”之一中定义的类时,我收到一条错误消息,指出它在当前上下文中不存在。

我显然做错了什么。有人知道传递给 CSharpCompilationOptions 类时使用列表的用途吗?

这是代码:

public static void TestMethod()
    {
        string source = @"public class Test
{
    public static void TestMethod()
    {
        string str = Directory.GetCurrentDirectory();
    }
}";
        SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source);

        List<string> usings = new List<string>()
        {
            "System.IO", "System"
        };
        List<MetadataFileReference> references = new List<MetadataFileReference>()
        {
            new MetadataFileReference(typeof(object).Assembly.Location),
        };   

        //adding the usings this way also produces the same error
        CompilationUnitSyntax root = (CompilationUnitSyntax)syntaxTree.GetRoot();
        root = root.AddUsings(usings.Select(u => SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName(u))).ToArray());
        syntaxTree = CSharpSyntaxTree.Create(root);

        CSharpCompilationOptions options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, usings: usings);
        CSharpCompilation compilation = CSharpCompilation.Create("output", new[] { syntaxTree }, references, options);

        using (MemoryStream stream = new MemoryStream())
        {
            EmitResult result = compilation.Emit(stream);

            if (result.Success)
            {
            }
        }
    }

最佳答案

因此,事实证明 CSharpCompilationOptions.Usings 仅在编译脚本文件时在编译器中进行过检查。如果您跟踪引用资料,它最终会被使用 here , 在 if (inScript) 检查中。

我们可能需要更好地记录这一点。

关于c# - Roslyn - CSharpCompilation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24658381/

相关文章:

c# - 使用 Linq 动态查询数据集

c# - Roslyn - 如何将多个节点分别替换为多个节点?

.net - .net 核心项目使用 <DebugType>Full</DebugType> 和 <DebugType>Portable</DebugType> 有什么区别?

c# - 从 Roslyn 中的行号获取节点

c# - 如何以编程方式向项目添加程序集引用?

c# - Roslyn 如何帮助我避免重新编译以将更改部署到我的 ASP.NET 网站?

c# - 以编程方式创建按钮单点触控

c# - 如何获取泛型类型的类型参数?

c# - Excel 中的行循环

c# - 通过单击复选框检查列表中的所有复选框