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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/949246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:02:16  来源:igfitidea点击:

How can I get all classes within a namespace?

c#.netreflectionnamespaces

提问by

How can I get all classes within a namespace in C#?

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

采纳答案by Fredrik M?rk

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

回答by Gerrie Schenck

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 属性,你可以用它来过滤你感兴趣的命名空间。

回答by Eoin Campbell

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)