[英]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.