Find Types in All Assemblies

后端 未结 4 1010
南笙
南笙 2020-12-05 06:27

I need to look for specific types in all assemblies in a web site or windows app, is there an easy way to do this? Like how the controller factory for ASP.NET MVC looks acr

4条回答
  •  再見小時候
    2020-12-05 06:43

    Most commonly you're only interested in the assemblies that are visible from the outside. Therefor you need to call GetExportedTypes() But besides that a ReflectionTypeLoadException can be thrown. The following code takes care of these situations.

    public static IEnumerable FindTypes(Func predicate)
    {
        if (predicate == null)
            throw new ArgumentNullException(nameof(predicate));
    
        foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
        {
            if (!assembly.IsDynamic)
            {
                Type[] exportedTypes = null;
                try
                {
                    exportedTypes = assembly.GetExportedTypes();
                }
                catch (ReflectionTypeLoadException e)
                {
                    exportedTypes = e.Types;
                }
    
                if (exportedTypes != null)
                {
                    foreach (var type in exportedTypes)
                    {
                        if (predicate(type))
                            yield return type;
                    }
                }
            }
        }
    }
    

提交回复
热议问题