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

查看:67
本文介绍了使用反射(DotNET)在程序集中查找所有命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序集(作为ReflectionOnly加载),我想找到该程序集中的所有名称空间,以便可以将它们转换为自动生成的源代码文件的"using"(在VB中为"Imports")语句.模板.

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属性,但是有没有一种更好的方法来收集程序集中的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)在程序集中查找所有命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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