如何在一个名称空间中获取所有类?

如何在 C # 中获得一个名称空间中的所有类?

107858 次浏览

With Reflection you cal loop through all the types in an assembly. A type has a Namespace property which you use to filter only the namespace you're interested in.

You'll need to provide a little more information...

Do you mean by using Reflection. You can iterate through an assemblies Manifest and get a list of types using

   System.Reflection.Assembly myAssembly = Assembly.LoadFile("");


myAssembly.ManifestModule.FindTypes()

If it's just in Visual Studio, you can just get the list in the intellisense window, or by opening the Object Browser (CTRL+W, J)

You will need to do it "backwards"; list all the types in an assembly and then checking the namespace of each type:

using System.Reflection;
private Type[] GetTypesInNamespace(Assembly assembly, string nameSpace)
{
return
assembly.GetTypes()
.Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal))
.ToArray();
}

Example of usage:

Type[] typelist = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "MyNamespace");
for (int i = 0; i < typelist.Length; i++)
{
Console.WriteLine(typelist[i].Name);
}

For anything before .Net 2.0 where Assembly.GetExecutingAssembly() is not available, you will need a small workaround to get the assembly:

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);
}