我有以下代码:
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工作正常)
答案 0 :(得分:3)
使用GetDeclaredSymbol进行节点声明。
// node is methodDeclaration or invocationExpression
var methodSymbol = model.GetSymbolInfo(node).Symbol ?? model.GetDeclaredSymbol(node);