Get dependencies between classes in Roslyn

混江龙づ霸主 提交于 2019-12-04 09:55:33

问题


I am successfully getting dependencies between projects with Roslyn, and now I would like to get dependencies between classes, similar to the Code Map feature in Visual Studio Enterprise.

Here is my code, the "?????" part is where I imagine I could get something. I am very new to the Roslyn API, though, and I don't know how to proceed from there on.

        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:


I'm not sure about your requirements, but you can probably go for checking all descendant SyntaxNodes of the class and get the corresponding symbol, and it's type, and then collect these types. Something like the following:

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

Note that there can be multiple typesForCurrentClass for a given class symbol because of partial classes.



来源:https://stackoverflow.com/questions/39235100/get-dependencies-between-classes-in-roslyn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!