简体   繁体   中英

How to find all usages of a MethodDeclarationSyntax in solution with Roslyn

I have the following code:

        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;

How can I find all the usages within a solution given a MethodDeclarationSyntax? (for the InvocationExpressionSyntax works ok)

Use GetDeclaredSymbol for node declarations.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM