在所有组件中查找types

我需要在网站或Windows应用程序的所有程序集中查找特定的types,有没有简单的方法来做到这一点? 就像ASP.NET MVC的控制器工厂如何查看控制器的所有组件一样。

谢谢。

有两个步骤来实现这一点:

  • AppDomain.CurrentDomain.GetAssemblies()为您提供当前应用程序域中加载的所有程序集。
  • Assembly类提供了一个GetTypes()方法来检索特定程序GetTypes()所有types。

因此你的代码可能看起来像这样:

 foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) { foreach (Type t in a.GetTypes()) { // ... do something with 't' ... } } 

要查找特定的types(例如,实现一个给定的接口,从一个共同的祖先inheritance或其他),你将不得不过滤结果。 如果您需要在应用程序中的多个位置执行此操作,则build立一个提供不同选项的帮助器类是一个不错的主意。 例如,我通常应用名称空间前缀filter,接口实现filter和inheritancefilter。

有关详细的文档,请在这里和这里查看MSDN。

轻松使用Linq:

 IEnumerable<Type> types = from a in AppDomain.CurrentDomain.GetAssemblies() from t in a.GetTypes() select t; foreach(Type t in types) { ... } 

LINQ解决scheme,检查组件是否dynamic:

 /// <summary> /// Looks in all loaded assemblies for the given type. /// </summary> /// <param name="fullName"> /// The full name of the type. /// </param> /// <returns> /// The <see cref="Type"/> found; null if not found. /// </returns> private static Type FindType(string fullName) { return AppDomain.CurrentDomain.GetAssemblies() .Where(a => !a.IsDynamic) .SelectMany(a => a.GetTypes()) .FirstOrDefault(t => t.FullName.Equals(fullName)); } 

大多数情况下,您只对从外部可见的组件感兴趣。 因此,您需要调用GetExportedTypes()但除此之外,可以抛出ReflectionTypeLoadException 。 以下代码处理这些情况。

 public static IEnumerable<Type> FindTypes(Func<Type, bool> 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; } } } } }