问题描述
我有一个程序集(作为 ReflectionOnly 加载),我想在这个程序集中找到所有命名空间,以便我可以将它们转换为自动生成的源代码文件的使用"(VB 中的导入")语句模板.
I've got an assembly (loaded as ReflectionOnly) and I want to find all the namespaces in this assembly so I can convert them into "using" ("Imports" in VB) statements for an auto-generated source code file template.
理想情况下,我只想将自己限制在顶级命名空间,而不是:
Ideally I'd like to restrict myself to top-level namespaces only, so instead of:
using System;
using System.Collections;
using System.Collections.Generic;
你只会得到:
using System;
我注意到 System.Type 类上有一个 Namespace 属性,但是否有更好的方法来在不涉及迭代所有类型和剔除重复的命名空间字符串的程序集中收集命名空间?
I noticed there is a Namespace property on the System.Type class, but is there a better way to collect Namespaces inside an assembly that doesn't involve iterating over all types and culling duplicate namespace strings?
非常感谢,大卫
推荐答案
不,这没有捷径可走,尽管 LINQ 使它相对容易.例如,在 C# 中,原始的命名空间集"将是:
No, there's no shortcut for this, although LINQ makes it relatively easy. For example, in C# the raw "set of namespaces" would be:
var namespaces = assembly.GetTypes()
.Select(t => t.Namespace)
.Distinct();
要获得顶级命名空间,您可能应该编写一个方法:
To get the top-level namespace instead you should probably write a method:
var topLevel = assembly.GetTypes()
.Select(t => GetTopLevelNamespace(t))
.Distinct();
...
static string GetTopLevelNamespace(Type t)
{
string ns = t.Namespace ?? "";
int firstDot = ns.IndexOf('.');
return firstDot == -1 ? ns : ns.Substring(0, firstDot);
}
我很好奇为什么你只需要顶级命名空间……这似乎是一个奇怪的限制.
I'm intrigued as to why you only need top level namespaces though... it seems an odd constraint.
这篇关于使用反射 (DotNET) 在程序集中查找所有命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!