How do i get a list of classes in .NET

2019-07-21 04:16发布

I tried Assembly.ReflectionOnlyLoadFrom(@"path\System.Core.dll") and ReflectionOnlyLoad but i got exceptions and errors. How do i properly get all the namespaces/classes in an assembly?

For example i got this exception.

Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

标签: c# reflection
3条回答
仙女界的扛把子
2楼-- · 2019-07-21 04:55

Here is your answer to your question. I do not need to copy & paste it here for you, it might be greener to save space rather that copying code from the other thread. :-)

查看更多
一纸荒年 Trace。
3楼-- · 2019-07-21 04:56

If you can reference System.Core then

    List<string> namespaces = new List<string>();

    var refs = Assembly.GetExecutingAssembly().GetReferencedAssemblies();

    foreach (var rf in refs) {
        if (rf.Name == "System.Core")
        {
            var ass = Assembly.Load(rf);
            foreach (var tp in ass.GetTypes())
            {
                if (!namespaces.Contains(tp.Namespace))
                {
                    namespaces.Add(tp.Namespace);
                    Console.WriteLine(tp.Namespace);
                }
            }
        }
    }

If you cannot, you will need to attach to the AssemblyResolve event of the CurrentDomain and load all assemblies of types that System.Core.dll uses when loading the dll.

查看更多
放我归山
4楼-- · 2019-07-21 05:03

To load an assembly and then get a list of all types:

Assembly assembly = Assembly.ReflectionOnlyLoadFrom("System.Core.dll");
Type[] types = assembly.GetTypes();

Unfortunately this will throw an exception if any of the types exposed cannot be loaded, and sometimes this load failure cannot be avoided. In this case however the thrown exception contains a list of all types that were successfully loaded and so we can just do this:

Assembly assembly = Assembly.ReflectionOnlyLoadFrom("System.Core.dll");

Type[] types;
try
{
    types = assembly.GetTypes();
}
catch (ReflectionTypeLoadException ex)
{
    types = ex.Types;
}

This will give you a list of all types, including interfaces, structs, enums etc... (If you want just the classes then you can filter that list).

查看更多
登录 后发表回答