获取引用符号的方法名称



我有一个方法符号的引用,但我需要获取调用方法符号的方法的名称。知道如何从参考对象中提取此信息吗?这是代码:

var references = SymbolFinder.FindReferencesAsync(symbol, solution).Result;
if (references != null && references.Any())
{
foreach (var reference in references)
{
foreach (var location in reference.Locations)
{
// Get name of the method of the reference 
}
}
}

您需要检索SemanticModel以供参考,然后您应该获得包含引用的最内层封闭符号:

...
foreach (var location in reference.Locations)
{
if (location.Document.TryGetSemanticModel(out var referenceSemanticModel))
{
var enclosingSymbol = referenceSemanticModel.GetEnclosingSymbol(location.Location.SourceSpan.Start);
if (!(enclosingSymbol is null))
{
// NOTE: if your symbol are referenced by lambda then this name 
// would be the innermost enclosing member which contains lambda,
// so be careful
var name = enclosingSymbol.Name;
}
}
}

最新更新