Roslyn : How to get the Namespace of a DeclarationSyntax with Roslyn C#

这一生的挚爱 提交于 2019-12-23 08:04:12

问题


I have a c# solution that contains some class files. With Roslyn I am able to parse a solution to obtain a list of projects within the solution. From there, I can get the documents in each project. Then, I can get a list of every ClassDeclarationSyntax. This is the starting point.

        foreach (var v in _solution.Projects)
        {
            //Console.WriteLine(v.Name.ToString());
            foreach (var document in v.Documents)
            {
                SemanticModel model = document.GetSemanticModelAsync().Result;
                var classes = document.GetSyntaxRootAsync().Result.DescendantNodes().OfType<ClassDeclarationSyntax>();
                foreach(var cl in classes)
                {
// Starting around this point...
                    ClassDiagramClass cls = new ClassDiagramClass(cl, model);
                    diagramClasses.Add(cls);
                }
            }
        }

From these objects I want to be able to get the Namespace of the variables used within each class. See file 1 has a method "getBar()" that returns an object of type B.Bar. The namespace is important because it tells you which type of Bar is really being returned.

File1.cs

using B;
namespace A {
    public class foo(){
        public Bar getBar(){ return new Bar();}
    }
}

File2.cs

namespace B {
    public class Bar(){
    }
}

File3.cs

namespace C {
    public class Bar(){
    }
}

The issue is that I am not sure how to get to the Namespace value from where I am in the code right now. Any ideas?


回答1:


The namespace is semantic information, so you need to get it from the semantic model:

model.GetTypeInfo(cl).Type.ContainingNamespace


来源:https://stackoverflow.com/questions/29479200/roslyn-how-to-get-the-namespace-of-a-declarationsyntax-with-roslyn-c-sharp

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