删除块的内容

我正在编写一个带有Code Fix的Roslyn诊断程序。 如果有一个带有一个空catch块的try块,我想提供一个选项来删除catch块并用其内容替换try块。 我的问题是try块内容的外观。 我尝试使用Formatter,但这些行仍然过多地存在于一个级别。 这是我的代码:

private async Task 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);