使用反射 (DotNET) 查找程序集中的所有命名空间 [英] Finding all Namespaces in an assembly using Reflection (DotNET)

查看:20
本文介绍了使用反射 (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) 查找程序集中的所有命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆