如何获取命名空间中的所有类? [英] How can I get all classes within a namespace?
本文介绍了如何获取命名空间中的所有类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 C# 中获取命名空间中的所有类?
How can I get all classes within a namespace in 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();
}
用法示例:
Type[] typelist = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "MyNamespace");
for (int i = 0; i < typelist.Length; i++)
{
Console.WriteLine(typelist[i].Name);
}
<小时>
对于 .Net 2.0 之前 Assembly.GetExecutingAssembly()
不可用的任何内容,您需要一个小的解决方法来获取程序集:
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);
}
这篇关于如何获取命名空间中的所有类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文