如何在Roslyn的解决方案中找到MethodDeclarationSyntax的所有用法

时间:2017-06-11 11:05:11

标签: c# .net roslyn roslyn-code-analysis

我有以下代码:

        var ws = new AdhocWorkspace();
        var project = ws.AddProject("Sample", "C#");
        ws.TryApplyChanges(project.Solution);
        string text = @"
                    class C
                        {
                            private int counter = 0;

                            public void main()
                            {
                                Do();
                            }
                            public void Do()
                            {
                                counter++;
                            }
                        }
                        class D
                        {
                            private int counter = 0;

                            public void Foo()
                            {
                                var c = new C();
                                c.Do();
                            }
                        }";
        var sourceText = SourceText.From(text);
        var doc = ws.AddDocument(project.Id, "NewDoc", sourceText);
        var model = doc.GetSemanticModelAsync().Result;
        var methodDeclaration = doc.GetSyntaxRootAsync().Result.DescendantNodes().OfType<MethodDeclarationSyntax>().ToList()[1];
        var invocationExpression = doc.GetSyntaxRootAsync().Result.DescendantNodes().OfType<InvocationExpressionSyntax>().ToList()[0];
        //TODO: If I replace invocationExpression with methodDeclaration IT DOES NOT WORK
        var methodSymbol = model.GetSymbolInfo(invocationExpression ).Symbol;
        //Finds all references to M()
        var referencesToM = SymbolFinder.FindReferencesAsync(methodSymbol, doc.Project.Solution).Result;

如何在MethodDeclarationSyntax中找到解决方案中的所有用法? (对于InvocationExpressionSyntax工作正常)

1 个答案:

答案 0 :(得分:3)

使用GetDeclaredSymbol进行节点声明。

// node is methodDeclaration or invocationExpression
var methodSymbol = model.GetSymbolInfo(node).Symbol ?? model.GetDeclaredSymbol(node);