问题
I'm writing a Roslyn Diagnostic with Code Fix. If there's a try block with one empty catch block, i want to provide the option to remove the catch block and replace the try block with its content. My problem is the outdenting of the content of the try block. I tried using the Formatter, but the lines are still indentend one level too much. Here's my code:
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);
}
回答1:
Roslyn is very immutable, your Formatter
won't be changing the original node but instead return you a new one that is formatted.
Instead, try this:
var formattedRoot = Formatter.Format(newRoot, MSBuildWorkspace.Create());
return document.WithSyntaxRoot(formattedRoot);
来源:https://stackoverflow.com/questions/25013869/outdenting-of-content-of-removed-block