C#:列出程序集中的所有类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1315665/
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 15:02:25  来源:igfitidea点击:

C#: List All Classes in Assembly

c#.netclass-structure

提问by Alex

I'd like to output (programmatically - C#) a list of all classes in my assembly.

我想输出(以编程方式 - C#)我的程序集中所有类的列表。

Any hints or sample code how to do this? Reflection?

任何提示或示例代码如何做到这一点?反射?

采纳答案by Jon Skeet

Use Assembly.GetTypes. For example:

使用Assembly.GetTypes. 例如:

Assembly mscorlib = typeof(string).Assembly;
foreach (Type type in mscorlib.GetTypes())
{
    Console.WriteLine(type.FullName);
}

回答by Thorarin

I'd just like to add to Jon's example. To get a reference to your own assembly, you can use:

我只想补充乔恩的例子。要获得对您自己的程序集的引用,您可以使用:

Assembly myAssembly = Assembly.GetExecutingAssembly();

System.Reflectionnamespace.

System.Reflection命名空间。

If you want to examine an assembly that you have no reference to, you can use either of these:

如果要检查没有参考的程序集,可以使用以下任一方法:

Assembly assembly = Assembly.ReflectionOnlyLoad(fullAssemblyName);
Assembly assembly = Assembly.ReflectionOnlyLoadFrom(fileName);

If you intend to instantiate your type once you've found it:

如果您打算在找到类型后实例化它:

Assembly assembly = Assembly.Load(fullAssemblyName);
Assembly assembly = Assembly.LoadFrom(fileName);

See the Assembly class documentationfor more information.

有关更多信息,请参阅程序集类文档

Once you have the reference to the Assemblyobject, you can use assembly.GetTypes()like Jon already demonstrated.

一旦获得了Assembly对象的引用,就可以assembly.GetTypes()像 Jon 已经演示的那样使用。