2012-09-16 22 views
3

當調用System.Collections時,此代碼不返回任何名稱空間。如何返回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中有類型。我能做些什麼來獲得命名空間?

回答

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

通過使用LINQ您可以獲取組件的名稱空間。

+0

這只是另一種方式寫的代碼定義得到System.Collections.MyCollections。它仍然應該爲System.Collections程序集返回0個名稱空間。 – user1675878

1

不同的程序集可能包含相同的(或子)名稱空間。對於例如A.dll可能包含命名空間AB.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(); 

例如,如果你運行上面的代碼,你會不會因爲它在我的測試代碼SO.exe :)

+0

但是,如果我只想在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

相關問題