如何在C#的命名空间中获取所有类?
您将需要“向后”进行;列出程序集中的所有类型,然后检查每种类型的名称空间:
using System.Reflection; private Type[] GetTypesInNamespace(Assembly assembly, string nameSpace) { return assembly.GetTypes() .Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal)) .ToArray(); }
用法示例:
Type[] typelist = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "MyNamespace"); for (int i = 0; i < typelist.Length; i++) { Console.WriteLine(typelist[i].Name); }
对于.Net 2.0之前Assembly.GetExecutingAssembly()不可用的任何内容,您将需要一个小的解决方法来获取程序集:
Assembly.GetExecutingAssembly()
Assembly myAssembly = typeof(<Namespace>.<someClass>).GetTypeInfo().Assembly; Type[] typelist = GetTypesInNamespace(myAssembly, "<Namespace>"); for (int i = 0; i < typelist.Length; i++) { Console.WriteLine(typelist[i].Name); }