给定输入如下:
namespace Test
{
using System;
public class Test
{
public int? OBJECTID { get; set; }
}
}
我想让这个类扩展其他类。所以我用这些规则编写了我的重写器:
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
{
node =
node.WithBaseList(
SyntaxFactory.BaseList()
.WithTypes(
SyntaxFactory.SingletonSeparatedList<BaseTypeSyntax>(
SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseName("Form"))
.WithLeadingTrivia(SyntaxFactory.Space) //Space before 'Form'
.WithTrailingTrivia(SyntaxFactory.LineFeed) // NewLine after 'Form'
)
)
);
return base.VisitClassDeclaration(node);
}
但是我得到的输出如下所示:
namespace Test
{
using System;
public class Test
: Form
{
public int? OBJECTID { get; set; }
}
}
我已经尝试过WithoutTrailingTrivia()
和WithoutLeadingTrivia()
在许多不同的位置,但我找不到放置它的真正位置,以删除 ":"
之前的换行符.
你能帮我解决这个问题吗?
最佳答案
我使用扩展性工具中的语法可视化工具查看了示例中的语法树,其中插入符号位于类名后面。这为我提供了以下语法树:
如您所见,EndOfLineTrivia 与 IdentifierToken 关联。因此,您可以通过替换标识符来删除它(或替换它,如以下示例所示):
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
{
node = node.WithBaseList(
SyntaxFactory.BaseList()
.WithTypes(
SyntaxFactory.SingletonSeparatedList<BaseTypeSyntax>(
SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseName("Form"))
.WithLeadingTrivia(SyntaxFactory.Space)
.WithTrailingTrivia(SyntaxFactory.LineFeed)
)
)
);
node =
node.WithIdentifier(
node.Identifier.WithTrailingTrivia
(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " ")));
return base.VisitClassDeclaration(node);
}
关于c# - 添加继承时删除 ':' 之前的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38872027/