c# - 如何通过添加和删除从旧根检索到的节点来创建新根?

标签 c# roslyn

我正在创建一个代码修复来改变这个:

if(obj is MyClass)
{
    var castedObj = obj as MyClass;
}

进入这个:

var castedObj = obj as MyClass;
if(castedObj != null)
{
}

这意味着我必须做三件事:

  • 更改 if 语句中的条件。
  • 将转换移动到 if 语句的正上方。
  • 删除正文中的语句。

到目前为止,我的所有尝试都使我最多无法让其中的 2 个东西发挥作用。

我认为出现此问题是因为您基本上在同一级别上有 2 个语法节点。因此,对其中一个进行更改会使另一个的位置无效。或类似的东西。长话短说:我要么设法在 if 语句外复制变量赋值,要么设法更改条件 + 删除变量赋值。从来没有全部 3。

我该如何解决这个问题?

为了更好地衡量,这里是我的代码,它更改了条件并删除了分配:

var newIfStatement = ifStatement.RemoveNode(
                                   variableDeclaration,
                                   SyntaxRemoveOptions.KeepExteriorTrivia);
newIfStatement = newIfStatement.ReplaceNode(newIfStatement.Condition, newCondition);

var ifParent = ifStatement.Parent;
var newParent = ifParent.ReplaceNode(ifStatement, newIfStatement);
newParent = newParent.InsertNodesBefore(
                           newIfStatement, 
                           new[] { variableDeclaration })
                           .WithAdditionalAnnotations(Formatter.Annotation);

var newRoot = root.ReplaceNode(ifParent, newParent);

最佳答案

你看过DocumentEditor了吗?类(class) ?这在处理修改语法时非常有用,尤其是当应用于树的更改可能导致失效问题时。这些操作与您已经定义的操作几乎相同,只需改用 DocumentEditor 方法,看看是否有帮助。我无法验证这是否解决了您的 ATM 问题,但我认为它曾经为我解决过类似的问题。如果可以的话,我稍后会测试一下。

像这样的事情会做到这一点:

var editor = await DocumentEditor.CreateAsync(document);
editor.RemoveNode(variableDeclaration);
editor.ReplaceNode(ifStatement.Condition, newCondition);
editor.InsertBefore(ifStatement, 
     new[] { variableDeclaration.WithAdditionalAnnotations(Formatter.Annotation) });

var newDocument = editor.GetChangedDocument();

关于c# - 如何通过添加和删除从旧根检索到的节点来创建新根?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30562759/

相关文章:

c# - 如何使用 Roslyn 在 C# 中添加新运算符

c# - Roslyn 中的 VisitClassDeclaration node.Identifier

c# - Roslyn 在 {SomeSyntax}.Type 下获取详细信息

c# - 如何以异步方法向 UI 提供反馈?

c# - ASP MVC 编译时包含部分 View

unit-testing - 以编程方式运行 Roslyn 分析时启用 Roslyn 诊断

c# - C# 规范 7.16.2.5 中的不一致

c# 对象 obj 的值为 {}。什么是 "{}"?

c# - 尝试将数据插入 SQLite 数据库时数据类型不匹配

c# - 如何在 Winforms TextBox 中每次按键后获取当前文本?