Roslyn - CSharpCompilation

 fishdenise_496 发布于 2023-01-04 12:44

我正在使用CSharpCompilation该类来编译SyntaxTree根是类声明的位置.我向构造函数传递一个CSharpCompilationOptions包含我的using语句的对象.

我的理解是语法树将使用我传递的任何using语句的上下文进行编译.但是当试图访问一个'usings'中定义的类时,我传递给options对象,我得到一个错误,说它在当前上下文中不存在.

我显然做错了什么.有人知道传递给CSharpCompilationOptions班级时的使用清单是什么?

这是代码:

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

        List usings = new List()
        {
            "System.IO", "System"
        };
        List references = new List()
        {
            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)
            {
            }
        }
    }

Kevin Pilch.. 7

因此,事实证明,CSharpCompilationOptions.Usings编译脚本文件时只在编译器中检查过.如果您浏览引用,它最终会在此处使用,在if (inScript)检查中.

我们可能需要更好地记录.

1 个回答
  • 因此,事实证明,CSharpCompilationOptions.Usings编译脚本文件时只在编译器中检查过.如果您浏览引用,它最终会在此处使用,在if (inScript)检查中.

    我们可能需要更好地记录.

    2023-01-04 12:46 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有