查找解决方案中所有引用的位置

时间:2017-01-09 17:52:06

标签: c# roslyn projects-and-solutions roslyn-code-analysis find-all-references

我正在尝试使用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();
                              });

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

Null location

当我在VS(2015)中查找所有引用时 - 我确实得到了引用。

enter image description here

更新:

跟进@Slacks的建议我修复了代码,现在它正常工作。我将它发布在这里供将来参考googlers ...

    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;
        }
    }

1 个答案:

答案 0 :(得分:2)

您仅使用该源文件创建新的Compilation且没有相关参考。因此,该编辑中的符号不​​会起作用,当然也不会受到现有Solution中任何内容的约束。

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