[英]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: 要记住两点:
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.