Finding all Namespaces in an assembly using Reflection (DotNET)(使用反射 (DotNET) 查找程序集中的所有命名空间)
问题描述
我有一个程序集(作为 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 类上有一个命名空间属性,但是有没有更好的方法来收集程序集中的命名空间,而不涉及迭代所有类型和剔除重复的命名空间字符串?
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) 查找程序集中的所有命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用反射 (DotNET) 查找程序集中的所有命名空间


基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01