首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用Roslyn查找对某个方法的所有引用

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

Stack Overflow用户
提问于 2015-08-07 01:06:48
回答 2查看 18.2K关注 0票数 28

我希望扫描一组.cs文件,看看哪些文件调用了Nullable<T>Value属性(查找所有引用)。例如,这将匹配:

代码语言:javascript
运行
复制
class Program
{
    static void Main()
    {
        int? nullable = 123;
        int value = nullable.Value;
    }
}

我发现了Roslyn,并查看了一些示例,但其中许多都过时了,API非常庞大。我该怎么做呢?

在解析语法树之后,我被卡住了。这就是我到目前为止所知道的:

代码语言:javascript
运行
复制
public static void Analyze(string sourceCode)
{
    var tree = CSharpSyntaxTree.ParseText(sourceCode);

    tree./* ??? What goes here? */
}
EN

Stack Overflow用户

回答已采纳

发布于 2015-08-07 04:00:15

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

听起来你在熟悉Roslyn方面有些困难。我有一系列的博客帖子来帮助人们认识罗斯林,叫做Learn Roslyn Now

正如@SLaks提到的,您将需要访问我在Part 7: Introduction to the Semantic Model中介绍的语义模型

下面是一个示例,向您展示如何使用该API。如果可以,我会使用MSBuildWorkspace并从磁盘加载项目,而不是像这样在AdHocWorkspace中创建项目。

代码语言:javascript
运行
复制
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<InvocationExpressionSyntax>().First();
var methodSymbol = model.GetSymbolInfo(methodInvocation).Symbol;
//Finds all references to M()
var referencesToM = SymbolFinder.FindReferencesAsync(methodSymbol,  doc.Project.Solution).Result;
票数 54
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31861762

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档