Roslyn:如何使用Roslyn C#获取DeclarationSyntax的命名空间 [英] Roslyn : How to get the Namespace of a DeclarationSyntax with Roslyn C#

查看:216
本文介绍了Roslyn:如何使用Roslyn C#获取DeclarationSyntax的命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#解决方案,其中包含一些类文件.使用Roslyn,我可以解析解决方案以获得解决方案中的项目列表.从那里,我可以获取每个项目中的文档.然后,我可以获得每个ClassDeclarationSyntax的列表. 这是起点.

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);
                }
            }
        }

从这些对象中,我希望能够获取每个类中使用的变量的名称空间.请参阅文件1的方法"getBar()",该方法返回B.Bar类型的对象.命名空间很重要,因为它告诉您实际上返回的是哪种类型的Bar.

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?

推荐答案

名称空间是语义信息,因此您需要从语义模型中获取它:

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

model.GetTypeInfo(cl).Type.ContainingNamespace

这篇关于Roslyn:如何使用Roslyn C#获取DeclarationSyntax的命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆