繁体   English   中英

查找解决方案中所有参考的位置

[英]Finding location of all references across solution

我正在尝试使用Roslyn API查找解决方案中所有类型的所有引用。

当然,我确实获得了对类型的引用(使用SymbolFinder.FindReferencesAsync ),但是当我检查它们的位置(使用SymbolFinder.FindSourceDefinitionAsync )时,得到的结果为null

到目前为止,我尝试了什么?

我正在使用以下方法加载解决方案:
this._solution = _msWorkspace.OpenSolutionAsync(solutionPath).Result;

并使用以下方法获取参考:

List<ClassDeclarationSyntax> solutionTypes = this.GetSolutionClassDeclarations();

var res = solutionTypes.ToDictionary(t => t,
                              t =>
                              {
                                  var compilation = CSharpCompilation.Create("MyCompilation", new SyntaxTree[] { t.SyntaxTree }, new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) });
                                  var semanticModel = compilation.GetSemanticModel(t.SyntaxTree);
                                  var classSymbols = semanticModel.GetDeclaredSymbol(t);

                                  var references = SymbolFinder.FindReferencesAsync(classSymbols, this._solution).Result;
                                  foreach (var r in references)
                                  {
                                        //=== loc is allways null... ===
                                      var loc = SymbolFinder.FindSourceDefinitionAsync(r.Definition, this._solution).Result;
                                  }

                                  return references.ToList();
                              });

但是正如我所说,所有参考文献都没有位置。

空位置

当我在VS(2015)中查找所有参考文献时,确实获得了参考文献。

在此处输入图片说明


更新:

遵循@Slacks的建议,我已修复了代码,现在可以正常工作。 我将其发布在这里,以供Google员工参考。

    Dictionary<Project, List<ClassDeclarationSyntax>> solutionTypes = this.GetSolutionClassDeclarations();

    var res = new Dictionary<ClassDeclarationSyntax, List<ReferencedSymbol>>();
    foreach (var pair in solutionTypes)
    {
        Project proj = pair.Key;
        List<ClassDeclarationSyntax> types = pair.Value;
        var compilation = proj.GetCompilationAsync().Result;
        foreach (var t in types)
        { 
            var references = new List<ReferencedSymbol>();

            var semanticModel = compilation.GetSemanticModel(t.SyntaxTree);
            var classSymbols = semanticModel.GetDeclaredSymbol(t);

            references = SymbolFinder.FindReferencesAsync(classSymbols, this._solution).Result.ToList();

            res[t] = references;
        }
    }

您正在使用该源文件创建新Compilation ,而没有相关参考。 因此,该编译中的符号将不起作用,并且当然也不会与您现有Solution任何内容绑定。

您需要从包含节点的Project中获取Compilation

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM