[英]Roslyn : How to get the Namespace of a DeclarationSyntax with Roslyn C#
I have ac# solution that contains some class files. 我有一个包含一些类文件的ac#解决方案。 With Roslyn I am able to parse a solution to obtain a list of projects within the solution.
通过Roslyn,我能够解析解决方案以获得解决方案中的项目列表。 From there, I can get the documents in each project.
从那里,我可以在每个项目中获取文档。 Then, I can get a list of every ClassDeclarationSyntax.
然后,我可以获得每个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.
参见文件1有一个方法“getBar()”,它返回一个B.Bar类型的对象。 The namespace is important because it tells you which type of Bar is really being returned.
命名空间很重要,因为它告诉您实际返回的是哪种类型的Bar。
File1.cs File1.cs
using B;
namespace A {
public class foo(){
public Bar getBar(){ return new Bar();}
}
}
File2.cs File2.cs
namespace B {
public class Bar(){
}
}
File3.cs 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. 问题是我不知道如何从代码中的位置获取Namespace值。 Any ideas?
有任何想法吗?
命名空间是语义信息,因此您需要从语义模型中获取它:
model.GetTypeInfo(cl).Type.ContainingNamespace
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.