简体   繁体   English

如何递归地获取命名空间内的所有命名空间

[英]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: 听起来你可能想要从命名空间到类的Lookup

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

Or alternatively (and very similarly) you could use GroupBy : 或者(也可以非常相似)你可以使用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. 就CLR而言,命名空间实际上并不构成层次结构。 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. C#语言本身确实有一些规则,但就CLR而言,没有“父”命名空间这样的东西。

If you really want to go from "Foo.Bar.Baz" to "Foo.Bar" and "Foo" then you can use something like: 如果你真的想从“Foo.Bar.Baz”到“Foo.Bar”和“Foo”那么你可以使用类似的东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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