并非所有InvocationExpression都被重写

时间:2020-02-27 03:31:09

标签: .net-core roslyn

我想重写SyntaxTree中“ MyMethod”的所有InvocationExpression,以添加文字参数0,

private class Rewriter : CSharpSyntaxRewriter
    {
        public int Id { get; set; }
        public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node)
        {
            var invokName = node.Expression.ToString();
            if (invokName == "MyMethod")
            {
                var argus = node.ArgumentList.AddArguments(
SyntaxFactory.Argument(SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(Id))));
                return node.Update((ExpressionSyntax)Visit(node.Expression), argus);
            }
            return node;
        }
    }
    static void Main(string[] args)
    {
        SyntaxTree oriTree = CSharpSyntaxTree.ParseText(@"
        public class MyClass
        {
            public string MyMethod(int id)
            {
                return $""{id}"";
            }
            public void Say()
            {
                var tmp = MyMethod();//worked
                var tmp1 = MyMethod();//worked
                var tmp2 = ""Hi "" + MyMethod();//worked
                Console.WriteLine($""Say {MyMethod()}"");//Not worked
                Console.WriteLine(""Hello "" + MyMethod());//Not worked                    
            }
        }");
        var syntaxRoot = oriTree.GetCompilationUnitRoot();
        var visitor = new Rewriter();
        visitor.Id = 0;
        var changedSyntaxTree = visitor.Visit(syntaxRoot).SyntaxTree;
    }

但并非所有内容都被重写。

使用

var methods = syntaxRoot.DescendantNodes().OfType<InvocationExpressionSyntax>().Where(o => o.Expression.ToString() == "MyMethod");

我可以枚举“ MyMethod”的所有InvocationExpression。但是我不知道如何在没有CSharpSyntaxRewriter的情况下更改语法树。

我该怎么办?谢谢。

1 个答案:

答案 0 :(得分:0)

它基于CyrusNajmabadi的reply

解决了

您需要执行以下操作:

      public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node)
        {
            node = (InvocationExpressionSyntax)base.VisitInvocationExpression(node);
            // now, the rest of your code:
            var invokName = node.Expression.ToString();
            // etc.

感谢CyrusNajmabadi!