我试图在一个类型的解决方案中找到所有引用。我的起点是文件内的一个跨度(当前光标位置),如 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/