如何返回 System.Collections 程序集中命名空间列表?

3
当针对System.Collections调用时,此代码不返回任何命名空间。
public static List<string> GetAssemblyNamespaces(AssemblyName asmName)
{
  List<string> namespaces = new List<string>();
  Assembly asm = Assembly.Load(asmName);

  foreach (Type typ in asm.GetTypes())
    if (typ.Namespace != null) 
      if (!namespaces.Contains(typ.Namespace))
        namespaces.Add(typ.Namespace);

  return namespaces;
}

为什么会这样呢?System.Collections 中有许多类型。我应该怎么办才能获取名称空间呢?

2个回答

1
不同的程序集可能包含相同(或子)命名空间。例如,A.dll 可能包含命名空间 A ,而 B.dll 可能包含 A.B。因此,您必须加载 所有 程序集才能查找命名空间。
这可能会起作用,但仍然存在一个问题,即命名空间可能在未被引用、未被使用的程序集中。
var assemblies = new List<AssemblyName>(Assembly.GetEntryAssembly().GetReferencedAssemblies());
assemblies.Add(Assembly.GetEntryAssembly().GetName());

var nss = assemblies.Select(name => Assembly.Load(name))
            .SelectMany(asm => asm.GetTypes())
            .Where(type=>type.Namespace!=null)
            .Where(type=>type.Namespace.StartsWith("System.Collections"))
            .Select(type=>type.Namespace)
            .Distinct()
            .ToList();

例如,如果您运行上面的代码,您将无法获得System.Collections.MyCollections,因为它是在我的测试代码SO.exe中定义的 :)

但是如果我只想要 System.Collections.dll 中的命名空间,为什么需要加载其他任何程序集呢?根据文档(.NET 4.5),此程序集包含五个命名空间(System.Collections、System.Collections.Concurrent、System.Collections.Generic、System.Collections.ObjectModel、System.Collections.Specialized)。你的意思是它们不在 System.Collections.dll 中,而是在被 System.Collections.dll 引用的其他程序集中吗?!但主要问题确实是为什么 GetTypes() 不返回任何类型。System.Collections.dll 中有像 ArrayList、Stack 等类型。 - user1675878

0
var namespaces = assembly.GetTypes()
                         .Select(t => t.Namespace)
                         .Distinct();

通过使用 LINQ,您可以获取程序集的命名空间。


这只是另一种编写代码的方式。它仍应返回System.Collections程序集的0个命名空间。 - user1675878

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接