Roslyn深入替换SyntaxNodes

时间:2019-04-06 17:13:18

标签: c# roslyn

作为示例,我想向cs文件中的类,构造函数和方法添加XML注释。我尝试不同的方法,并且当我保持相同的SyntaxNode深度时,一切正常。但是下面的最小示例声明了我的问题。

turtle.onscreenclick()

解决此用例的通常方法是什么?谁可以更新类SyntaxNode和方法SyntaxNode?

感谢您的回复!

解决方案:

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Linq;

namespace Tools.Tester
{
    class Stackoverflow
    {
        public static void Question()
        {
            SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(
            @"
            public class Class
            {
                public void Method(){}
            }
            "
            );

            //REPLACE CLASS
            SyntaxNode Class = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().First();
            SyntaxNode ClassNew = Class.WithLeadingTrivia(SyntaxFactory.ParseLeadingTrivia("///<summery>XML</summery>").Add(SyntaxFactory.EndOfLine("\n")));

            /*CLASS SHOULD NOW:
            ///<summery>XML</summery>
            public class Class
            {
                public void Method(){}
            }
            */

            //REPLACE METHOD
            SyntaxNode Method = Class.DescendantNodes().OfType<MethodDeclarationSyntax>().First();
            SyntaxNode MethodNew = Method.WithLeadingTrivia(SyntaxFactory.ParseLeadingTrivia("///<summery>XML</summery>").Add(SyntaxFactory.EndOfLine("\n")));

            /*METHOD SHOULD NOW:
            ///<summery>XML</summery>
            public void Method(){}                
            */

            ClassNew = ClassNew.ReplaceNode(Method, MethodNew);
            /*CLASS SHOULD NOW:
            ///<summery>XML</summery>
            public class Class
            {
                ///<summery>XML</summery>
                public void Method(){}
            }
            */

            //UPDATE TREE
            SyntaxTree treeNew = SyntaxFactory.ParseSyntaxTree(tree.GetRoot().ReplaceNode(Class, ClassNew).GetText());
            string code = treeNew.GetText().ToString();
            Console.WriteLine(code);

            /*RESULT:
            ///<summery>XML</summery>
            public class Class
            {                
                public void Method(){}
            }
            */
        }
    }
}

0 个答案:

没有答案