使用Roslyn查找对方法的所有引用

我正在寻找扫描一组.cs文件,以查看哪些调用NullableValue属性(查找所有引用)。 例如,这将匹配:

 class Program { static void Main() { int? nullable = 123; int value = nullable.Value; } } 

我发现了Roslyn并查看了一些样本,但其中许多已经过时且API非常庞大。 我该怎么做呢?

解析语法树后我陷入了困境。 这是我到目前为止:

 public static void Analyze(string sourceCode) { var tree = CSharpSyntaxTree.ParseText(sourceCode); tree./* ??? What goes here? */ } 

您可能正在寻找SymbolFinder类,特别是FindAllReferences方法。

听起来你在熟悉Roslyn时遇到了一些麻烦。 我有一系列博客文章,以帮助人们介绍Roslyn,名为Learn Roslyn Now 。

正如@SLaks所提到的,你将需要访问我在第7部分:语义模型简介中介绍的语义模型

这是一个示例,向您展示如何使用API​​。 如果你能够,我将使用MSBuildWorkspace并从磁盘加载项目,而不是像这样在AdHocWorkspace中创建它。

 var mscorlib = PortableExecutableReference.CreateFromAssembly(typeof(object).Assembly); var ws = new AdhocWorkspace(); //Create new solution var solId = SolutionId.CreateNewId(); var solutionInfo = SolutionInfo.Create(solId, VersionStamp.Create()); //Create new project var project = ws.AddProject("Sample", "C#"); project = project.AddMetadataReference(mscorlib); //Add project to workspace ws.TryApplyChanges(project.Solution); string text = @" class C { void M() { M(); M(); } }"; var sourceText = SourceText.From(text); //Create new document var doc = ws.AddDocument(project.Id, "NewDoc", sourceText); //Get the semantic model var model = doc.GetSemanticModelAsync().Result; //Get the syntax node for the first invocation to M() var methodInvocation = doc.GetSyntaxRootAsync().Result.DescendantNodes().OfType().First(); var methodSymbol = model.GetSymbolInfo(methodInvocation).Symbol; //Finds all references to M() var referencesToM = SymbolFinder.FindReferencesAsync(methodSymbol, doc.Project.Solution).Result;