简体   繁体   English

如何获得名称空间中的所有类?

[英]How can I get all classes within a namespace?

如何在C#的命名空间中获取所有类?

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: 对于.Net 2.0之前不存在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);
}

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) 如果只是在Visual Studio中,则可以在智能感知窗口中获取列表,或通过打开对象浏览器(CTRL + W,J)

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. 类型具有Namespace属性,可用于仅过滤您感兴趣的名称空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM