c# - 编译 CompilationUnitSyntax 的正确方法

标签 c# roslyn

我有以下代码片段

 var compilationUnit = SyntaxFactory.CompilationUnit()
            .AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System")))
            .AddMembers(
                SyntaxFactory.NamespaceDeclaration(SyntaxFactory.IdentifierName("MyNamespace"))
                    .AddMembers(SyntaxFactory.ClassDeclaration("MyClass").AddMembers(
                        SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName("void"), "Main")
                            .WithBody(SyntaxFactory.Block())))).NormalizeWhitespace();

但是,当我直接从编译单元使用 SyntaxTree 时,似乎我无法使用 Roslyn 编译它 - 就像那样

        CSharpCompilation compilation = CSharpCompilation.Create(
           assemblyName: "MyAssembly",
           syntaxTrees: new [] { compilationUnit.SyntaxTree },
           references: references,
           options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
       );

我找不到比用

重新创建 SyntaxTree 更好的方法了
CSharpSyntaxTree.ParseText(compilationUnit.ToFullString())

并将其传递给 CSharpCompilation.Create 方法。有没有更好的方法来编译 CompilationUnitSyntax ?

最佳答案

从语法树创建编译的方式没有任何问题。问题在于您创建语法树的方式,特别是 void 关键字(如错误所示)。

如果你写这段代码:

SyntaxFactory.ParseTypeName("void").GetDiagnostics()

那么它已经报错了。

您可以手动为 void 类型创建一个 TypeName 对象,而不是 ParseTypeName:

SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword))

适合我的完整代码(从您的代码中简化以删除不必要的语法节点):

var compilationUnit = SyntaxFactory.CompilationUnit()
    .AddMembers(SyntaxFactory.ClassDeclaration("MyClass").AddMembers(
        SyntaxFactory.MethodDeclaration(
                SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)),
                "Main")
            .WithBody(SyntaxFactory.Block())))
    .NormalizeWhitespace();

CSharpCompilation compilation = CSharpCompilation.Create(
    assemblyName: "MyAssembly",
    syntaxTrees: new[] { compilationUnit.SyntaxTree },
    references: references,
    options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
);

关于c# - 编译 CompilationUnitSyntax 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41420297/

相关文章:

roslyn - 如何使用 Roslyn 获取 IEnumerable<T> 的基础类型?

c# - 实例化后的类实例为空

c# - 执行多个查询

c# - 如何使用空格将另一个变量插入到字符串中? C#

mono - CSC : error CS0041: Unexpected error writing debug information -- 'Operation is not supported on this platform.'

c# - C#字符串插值是如何编译的?

roslyn - SyntaxGenerator 和 SyntaxFactory 有什么区别?

c# - 为什么堆栈在 Exception.StackTrace 中被截断?

c# - CookieContainer : The 'Path' part of the cookie is invalid 的 CookieException

c# - lambda 表达式中的枚举的编译方式不同;重载分辨率改进的结果?