获取Roslyn中的类之间的依赖关系

时间:2016-08-30 18:55:22

标签: c# roslyn roslyn-code-analysis

我成功地获得了与Roslyn的项目之间的依赖关系,现在我想获得类之间的依赖关系,类似于Visual Studio Enterprise中的代码映射功能。

这是我的代码,“?????”部分是我想象的我能得到的东西。我是Roslyn API的新手,我不知道如何从那里开始。

        Solution solution = MSBuildWorkspace.Create()
            .OpenSolutionAsync(Path.Combine(repoRootFolder, "MySolution.sln"))
            .Result;

        ProjectDependencyGraph projdeps = solution.GetProjectDependencyGraph();

        Digraph graph = new Digraph();

        foreach (ProjectId projectId in projdeps.GetTopologicallySortedProjects())
        {
            string projName = solution.GetProject(projectId).Name;
            var projDeps = projdeps.GetProjectsThatThisProjectDirectlyDependsOn(projectId);
            foreach (ProjectId depId in projDeps)
            {
                Project dep = solution.GetProject(depId);

                Compilation compilation = dep.GetCompilationAsync().Result;

                foreach (var syntree in compilation.SyntaxTrees)
                {
                    foreach (var classNode in syntree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>())
                    {
                        var classesThisClassNodeReferences = ?????????
                    }
                }

                string depName = dep.Name;

                graph.Dependencies.Add(new Dependency
                {
                    Source = projName,
                    Target = depName
                });
            }
        }

1 个答案:

答案 0 :(得分:5)

我不确定你的要求,但你可以去检查班级的所有后代SyntaxNode并得到相应的符号,它是类型,然后收集这些类型。如下所示:

var semantic = compilation.GetSemanticModel(syntree);
var typesForCurrentClass = classNode.DescendantNodes().Select(n => 
  semantic.GetTypeInfo(n).Type);

请注意,由于部分类,给定类符号可能有多个typesForCurrentClass