How do I get a list of all loaded Types in C#?

ぃ、小莉子 提交于 2020-01-12 14:11:29

问题


I need to retrieve all enums that were loaded from a given set of Assemblies.


回答1:


List<Type> list = new List<Type>();
foreach (Assembly ass in AppDomain.CurrentDomain.GetAssemblies())
{
    foreach (Type t in ass.GetExportedTypes())
    {
        if (t.IsEnum)
        {
            list.Add(t);
        }
    }
}

That should do, for all assemblies loaded by the current Appdomain, to get just from defined assemblies, just adjust ;-)




回答2:


Here is a more functional solution:

AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(a => a.GetTypes())
    .Where(t => t.IsEnum)



回答3:


Assuming you have the list of Assembly objects you want to check:

IEnumerable<Assembly> assemblies; // assign the assemblies you want to check here

foreach (Assembly a in assemblies) {
    foreach (Type t in assembly.GetTypes()) {
        if (t.IsEnum) {
            // found an enum! Do whatever...
        }
    }
}



回答4:


You should be able to use Assembly.GetTypes() to get all the types for the assembly. For each type, you can use Type.IsEnum property to see if it's an enum.




回答5:


You can also use LINQ to return a list of all enum types from a list of assemblies.

IEnumerable<Assembly> assemblies;
// give assemblies some value
var enums = from assembly in assemblies let types = assembly.GetTypes() from type in types where type.IsEnum select type;

enums will be of type IEnumerable.



来源:https://stackoverflow.com/questions/1914058/how-do-i-get-a-list-of-all-loaded-types-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!