简体   繁体   English

从 Roslyn SyntaxTree 中删除所有 SyntaxTrivia 节点

[英]Remove all SyntaxTrivia nodes from Roslyn SyntaxTree

I am trying to remove all nodes of type SyntaxTrivia from a SyntaxTree using Roslyn.我正在尝试使用 Roslyn 从SyntaxTree删除SyntaxTrivia类型的所有节点。

I tried to use the SyntaxRewriter class, but that does not work as SyntaxTrivia is non-nullable:我尝试使用SyntaxRewriter类,但这不起作用,因为SyntaxTrivia不可为空:

public class WhitespaceRemover : CSharpSyntaxRewriter
{
   public override SyntaxTrivia VisitTrivia(SyntaxTrivia trivia)
   {
       // Cannot convert null to 'SyntaxTrivia' because it is a non-nullable value type
       return null;
   }
}

What's the correct way to accomplish this?实现这一目标的正确方法是什么?

I suppose that you need to rewrite a SyntaxNode invoking Microsoft.CodeAnalysis.SyntaxNodeExtensions.WithoutTrivia(...) , which will removes all trivias, instead of try to rewrite a SyntaxtTrivia .我想您需要重写一个SyntaxNode调用Microsoft.CodeAnalysis.SyntaxNodeExtensions.WithoutTrivia(...) ,这将删除所有琐事,而不是尝试重写SyntaxtTrivia

Upd.更新。 @Emiswelt correctly mentioned that should override Visit method and additionally overriding VisitTrivia in the comment, which allows to remove non atached trivias from SyntaxTree @Emiswelt 正确地提到应该在评论中覆盖Visit方法并另外覆盖VisitTrivia ,这允许从SyntaxTree删除非附加的SyntaxTree

You can use it inside your syntax rewrite and it will looks like this:您可以在语法重写中使用它,它看起来像这样:

public class WhitespaceRemover : CSharpSyntaxRewriter
{
    public override SyntaxNode Visit(SyntaxNode node) => base.Visit(node).WithoutTrivia();

    public override SyntaxTrivia VisitTrivia(SyntaxTrivia trivia) => default;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM