Roslyn: How to get a Syntax declaration namespace with Roslyn C #

I have a C # solution that contains some class files. With Roslyn, I can parse the solution to get a list of projects within the solution. From there I can get documents in every project. Then I can get a list of all 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 get the namespace of the variables used in each class. See File 1 has a getBar () method that returns an object of type B.Bar. The namespace is important because it tells you what type of bar is really coming back.

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 problem is that I'm not sure how to get to the Namespace value, where I am in the code from now. Any ideas?

+6
source share
1 answer

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

 model.GetTypeInfo(cl).Type.ContainingNamespace 
+6
source

Source: https://habr.com/ru/post/984760/


All Articles