在Roslyn中查找私人会员的推荐信

时间:2017-12-10 00:03:36

标签: c# roslyn code-analysis member roslyn-code-analysis

我想找到一个私有成员的所有引用。 我试过这样做:

MemberInfo member = ...//the private member for which I want to find its references 
Type type = member.DeclaringType;
string assemblyName = type.Assembly.GetName().Name;
Solution solution = workspace.CurrentSolution;
Project project = solution.Projects.First(x => x.AssemblyName == assemblyName);
Compilation compilation = project.GetCompilation();
ClassDeclarationSyntax classDeclaration = compilation.GetClassDeclaration(type);
MemberDeclarationSyntax memberDeclaration = classDeclaration.GetMemberDeclaration(member.Name);
SemanticModel semanticModel = compilation.GetSemanticModel(classDeclaration.SyntaxTree);
ISymbol memberSymbol = semanticModel.GetSymbolInfo(memberDeclaration).Symbol; ==> this is null since GetSymbolInfo does not expect a MemberDeclaationSyntax
IEnumerable<ReferencedSymbol> references = SymbolFinder.FindReferencesAsync(memberSymbol, solution).Result;

如何找到私人会员的所有参考资料?

1 个答案:

答案 0 :(得分:0)

因为MemberDeclarationSyntax是一个SyntaxNode,所以您需要使用Semantic.GetDeclaredSymbol方法来获取与此节点关联的符号。例如:

var memberDeclarationSyntax = ( MemberDeclarationSyntax ) root.FindNode( diagnostic.Location.SourceSpan );
var declaredSymbol = semanticModel.GetDeclaredSymbol( memberDeclarationSyntax );
var references = await SymbolFinder
    .FindReferencesAsync( declaredSymbol , context.Document.Project.Solution )
    .ConfigureAwait( false );