gpt4 book ai didi

c# - 如何使用 Roslyn 在解决方案中查找 MethodDeclarationSyntax 的所有用法

转载 作者:行者123 更新时间:2023-11-30 21:40:36 25 4
gpt4 key购买 nike

我有以下代码:

        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 工作正常)

最佳答案

使用 GetDeclaredSymbol 进行节点声明。

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

关于c# - 如何使用 Roslyn 在解决方案中查找 MethodDeclarationSyntax 的所有用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44483116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com