List namespaces in an assembly

I am trying to list all namespaces declared in an assembly. Doing something like this is very inconvenient:

foreach (var syntaxTree in context.Compilation.SyntaxTrees) { foreach (var ns in syntaxTree.GetRoot(context.CancellationToken).DescendantNodes().OfType<NamespaceDeclarationSyntax>()) { ... } } 

What is a good way to do this? A walk through the tree will be a bit nicer, but ask earlier, because I have a feeling that this is already somewhere in the API symbol.

+5
source share
2 answers

Calling compilation.Assembly.GlobalNamespace will give you a unified root namespace that contains all the namespaces defined in the source. The compilation.GlobalNamespace call will give you a root namespace that contains all the namespaces and types defined in the source code or referenced metadata.

From there, you will need to call GetNamespaceMembers recursively to get all the namespace characters:

 IEnumerable<INamespaceSymbol> GetAllNamespaces(INamespaceSymbol namespaceSymbol) { foreach (INamespaceSymbol symbol in namespaceSymbol.GetNamespaceMembers()) { yield return symbol; foreach (INamespaceSymbol childSymbol in GetAllNamespaces(symbol)) { yield return symbol; } } } var allNamespaceNodes = new List<NamespaceDeclarationSyntax>(); foreach (INamespaceSymbol namespaceSymbol in GetAllNamespaces(compilation.GlobalNamespace)) { allNamespaceNodes.AddRange(from syntaxReference in namespaceSymbol.DeclaringSyntaxReferences select syntaxReference.GetSyntax(cancellationToken) as NamespaceDeclarationSyntax); } 
+7
source

Found a method using Compilation , but feels like a hack.

 var namespaceSymbols = context .Compilation .GetSymbolsWithName(x => !string.IsNullOrEmpty(x), SymbolFilter.Namespace) .Cast<INamespaceSymbol>(); 
+6
source

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


All Articles