我试图在一个类型的解决方案中找到所有引用。我的起点是文件内的一个跨度(当前光标位置),如 110:116。查看 Roslyn 附带的示例,我发现我需要 SymbolFinder.FindReferencesAsync(theType, solution) 。我为测试解决方案创建了 File->NewProject,然后尝试:

  • 创建语法树
  • 加载解决方案
  • 使用树找到 Document//我在这里失败,返回 null
  • 提取 ISymbol (theType)//如何?

  • 我无法格式化代码 belo 所以这里有一个截图以便于阅读:
    string fileContent =
        @"using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;
        namespace APISampleUnitTestsCS
        {
            class Class1
            {
            }
        }";
    
    // it doesn;t matter if I supply or not the 2 and 3 parameters
    var tree = SyntaxFactory.ParseSyntaxTree(fileContent, "thePathTo_fileContent", new CSharpParseOptions());
    
    MSBuildWorkspace workspace = MSBuildWorkspace.Create();
    // Open the solution within the workspace.
    Microsoft.CodeAnalysis.Solution originalSolution = workspace.OpenSolutionAsync(dte.Solution.FileName).Result;
    
    // document is null
    var document = originalSolution.GetDocument(tree);
    
    //var textSpan = new Microsoft.CodeAnalysis.Text.TextSpan(textExtent.Span.Span.Start, asd.Span.Span.Length);
    var textSpan = new Microsoft.CodeAnalysis.Text.TextSpan(110, 116); //these values are for stackoverlow question
    
    // at least I can get TypeDeclarationSyntax. But how to extraxt the ISymbol???
    var tt = tree.GetRoot().FindNode(textSpan) as Microsoft.CodeAnalysis.CSharp.Syntax.TypeDeclarationSyntax;
    

    最佳答案

    solution.GetDocument(syntaxTree) 为您提供了在您调用 GetSyntaxTreeAsync 时为您提供语法树的文档。您不能将任意的语法树传递给它——只能从某个地方的文档中获得。它只是一个方便的 helper ,可以“返回”到文档的来源。

    我不太确定你想从片段中做什么,所以我将做出三个猜测:

  • 如果您尝试分析该解决方案中已经存在的文件,您应该使用在 originalSolution 中获得的解决方案对象并在那里找到文件文档。
  • 如果您想进行分析,就好像额外的树也添加到您的文档中一样,您可以调用 Solution.AddDocument() 将其添加为文档,然后您可以从那里分析它。记住 Roslyn 是不可变的,当你调用 Solution.AddDocument 时,你会得到一个新的解决方案来分析,所以捕获它给你的东西!
  • 如果您想要做的只是找到一个您已经知道名称的符号,请考虑在您的解决方案中找到包含该类型的项目,调用 GetCompilationAsync ,然后调用 GetTypeByMetadataName 或遍历命名空间以获取您的类型符号。
  • 关于c# - 无法使用 SyntaxTree 获取文档,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23399646/

    10-12 00:27
    查看更多