并非所有的 InvocationExpression 都被重写

Not all InvocationExpression are rewritten

我想在 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 的情况下更改语法树。

我该怎么做?谢谢

它根据 CyrusNajmabadi 的 reply

解决了

you need to do this instead:

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

谢谢 CyrusNajmabadi!