c# - 删除 block 的内容缩进

标签 c# roslyn

我正在编写带有代码修复的 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/

相关文章:

c# - 如何正确使用 Physics.autoSimulation?

c# - LINQ to Entities 无法识别方法 'System.Linq.IQueryable

c# - Roslyn SyntaxNodes 是否被重用?

c# - 从 Roslyn 的 goto 案例中获取符号

c# - 调试 Roslyn 分析器

c# - 为什么要批量发送电子邮件而不是单独发送?

c# - 如何使用制表符将字符串数组写入 Excel 文件?

c# - 样式化 WPF - 代码中的 Material Design GroupBox

c# - 在 Roslyn 的 .net core 中动态选择引用

c# - 使用 Roslyn 将自动实现的属性添加到类