Replacing multiple nodes in Roslyn syntax tree

前端 未结 1 658
时光说笑
时光说笑 2021-02-13 14:42

I\'m trying to replace a couple of nodes in a syntax tree using roslyn. But the immutable nature of it seems to get in my way.

    public static string Rewrite(s         


        
1条回答
  •  时光说笑
    2021-02-13 15:14

    I guess that the replacement changes the tree so that the other nodes no longer match the original tree and thus cant be replaced.

    You're right. Replacing nodes creates entirely new syntax trees. Nodes from previous syntax trees cannot be compared against these new syntax trees.

    There are four ways to apply multiple changes to a syntax tree:

    1. Use the DocumentEditor - See: https://stackoverflow.com/a/30563669/300908
    2. Use Annotations (Lines 236 and 240)
    3. Use .TrackNodes()
    4. Create a CSharpSyntaxRewriter that replaces nodes in a bottom-up approach. I've written about this on my blog.

    Of these options, I believe the DocumentEditor has the reputation for being the easiest to use. It may very well be the idiomatic way to apply multiple changes going forward.

    0 讨论(0)
提交回复
热议问题