我正在编写带有代码修复的 Roslyn 诊断。如果有一个 try block 和一个空的 catch block ,我想提供一个选项来删除 catch block 并用它的内容替换 try block 。我的问题是 try block 的内容缩进。我尝试使用 Formatter,但行仍然缩进了一级。这是我的代码:
private async Task<Document> RemoveTryCatchBlockAsync(Document document, TryStatementSyntax tryBlock, CancellationToken cancellationToken)
{
var oldRoot = await document.GetSyntaxRootAsync(cancellationToken);
var newRoot = oldRoot.ReplaceNode(tryBlock, tryBlock.Block.ChildNodes());
Formatter.Format(newRoot, MSBuildWorkspace.Create());
// Return document with transformed tree.
return document.WithSyntaxRoot(newRoot);
}
最佳答案
Roslyn 是非常不可变的,您的 Formatter
不会更改原始节点,而是返回一个经过格式化的新节点。
相反,试试这个:
var formattedRoot = Formatter.Format(newRoot, MSBuildWorkspace.Create());
return document.WithSyntaxRoot(formattedRoot);
关于c# - 删除 block 的内容缩进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25013869/