开发者

How to get all namespaces inside a namespace recursively

开发者 https://www.devze.com 2023-02-08 22:29 出处:网络
To put it simple, I want all the namespaces in the project recursively, and classes availablein all namespaces found earlier.

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

精彩评论

暂无评论...
验证码 换一张
取 消