How do I create a new root by adding and removing nodes retrieved from the old root?

前端 未结 2 1488
南笙
南笙 2020-12-09 05:21

I am creating a Code Fix that changes this:

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

into this:

var caste         


        
2条回答
  •  无人及你
    2020-12-09 06:00

    Have you looked at the DocumentEditor class ? It is very useful when dealing with modifying syntax, especially when the changes that are applied to the tree might cause invalidation problems. The operations are pretty much the same as the ones you already have defined, just use the DocumentEditor methods instead and see if that helps. I can't verify if that solves your problem ATM, but I think it solved the a similar problem for me once in the past. I'll test it out later if I can.

    Something like this will do it:

    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();
    

提交回复
热议问题