简体   繁体   中英

How to get all namespaces inside a namespace recursively

To put it simple, I want all the namespaces in the project recursively, and classes available in all namespaces found earlier.

var namespaces = assembly.GetTypes()
                  .Select(ns => ns.Namespace);

I am using this part earlier to get the namespaces in string format. But now i got to know the underlying namespaces as well.

It sounds like you might want a Lookup from namespace to class:

var lookup = assembly.GetTypes().ToLookup(t => t.Namespace);

Or alternatively (and very similarly) you could use GroupBy :

var groups = assembly.GetTypes().GroupBy(t => t.Namespace);

For example:

var groups = assembly.GetTypes()
                     .Where(t => t.IsClass) // Only include classes
                     .GroupBy(t => t.Namespace);
foreach (var group in groups)
{
    Console.WriteLine("Namespace: {0}", group.Key);
    foreach (var type in group)
    {
        Console.WriteLine("  {0}", t.Name);
    }
}

However, it's not entirely clear whether that's what you're after. That will get you the classes in each namespace, but I don't know whether that's really what you're looking for.

Two points to bear in mind:

  • There's nothing recursive about this
  • Namespaces don't really form a hierarchy, as far as the CLR is concerned. There's no such thing as an "underlying" namespace. The C# language itself does have some rules about this, but as far as the CLR is concerned, there's no such thing as a "parent" namespace.

If you really want to go from "Foo.Bar.Baz" to "Foo.Bar" and "Foo" then you can use something like:

while (true)
{
    Console.WriteLine(ns);
    int index = ns.LastIndexOf('.');
    if (index == -1)
    {
        break;
    }
    ns = ns.Substring(0, index);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM