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 中有类型。我能做些什么来获取命名空间?

4

2 回答 2

1

不同的程序集可能包含相同(或子)的命名空间。对于 exA.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:)

于 2012-09-16T17:06:47.623 回答
0
var namespaces = assembly.GetTypes()
                         .Select(t => t.Namespace)
                         .Distinct();

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

于 2012-09-16T16:15:11.067 回答