我正在使用 aSyntaxRewriter
将类从旧库转换为新库,这基本上需要查找具有给定属性的类,然后重写遵循特定约定的属性。重写器的一般骨架如下:
class PropertyConverter : SyntaxRewriter
{
public override SyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax node)
{
if (!MeetsUpdateCriteria(node)) return base.VisitPropertyDeclaration(node);
// these implementations simply return a string
var name = FigureOutName(node.Identifier);
var propertyType = FigureOutType(node.Type);
var getter = Syntax.ParseExpression("this.GetValue<" + propertyType + ">(" + name + ")");
var setter = Syntax.ParseExpression("this.SetValue(" + name + ", value)");
return node.WithType(propertyType)
.WithAccessorList(
Syntax.AccessorList(Syntax.List(
Syntax.AccessorDeclaration(
SyntaxKind.GetAccessorDeclaration,
Syntax.Block(Syntax.ReturnStatement(getter))),
Syntax.AccessorDeclaration(
SyntaxKind.SetAccessorDeclaration,
Syntax.Block(Syntax.ExpressionStatement(setter)))))));
}
}
这个转换器的结果是一个具有更新属性的类,它在以下代码中输出:
// IDocument csfile <- from a project in a Workspace
var tree = csfile.GetSyntaxTree();
var root = new PropertyConverter().Visit((SyntaxNode)tree.GetRoot())
.NormalizeWhitespace(); // problem!
File.WriteAllText(Path.GetFileName(csfile.FilePath), root.ToFullString());
此时代码在语法上都是正确的,并且输出的语法树是正确的。我唯一的抱怨是 XML 文档注释周围的空格根本不正确:
/// <summary>
/// Gets or sets the thickness (TH).
/// </summary>
public float Thickness
{
get
{
return this.GetValue<float>(TH);
}
set
{
this.SetValue(TH, value);
}
}
注意所有多余的缩进。此外,间距也以其他方式损坏,尤其是在方法文档中:
/// <summary>
/// Initializes a new instance of the <see cref = "X"/> class.
/// </summary>
/// <param name = "innerRadius">Inner radius of the X.</param>
/// <param name = "thickness">Thickness of the X.</param>
我已经验证了输入树没有遇到这些缩进问题,并且我还验证了该树在调用之前没有遇到这些缩进问题NormalizeWhitespace
。我也试过elasticTrivia: true
了,也没有任何运气。
那么如何让 Roslyn 以一致的方式规范化空白呢?