我有方法符号的引用,但我需要获取调用方法符号的方法的名称。知道如何从参考对象中提取此信息吗?这是代码:
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
}
}
}
答案 0 :(得分:1)
您需要检索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;
}
}
}