我需要在网站或Windows应用程序的所有程序集中查找特定类型,有没有简单的方法可以做到这一点?就像ASP.NET MVC的控制器工厂一样,在所有程序集中查找控制器。
谢谢。
谢谢。
实现这个功能需要两步:
AppDomain.CurrentDomain.GetAssemblies()
方法可以获取当前应用程序域中加载的所有程序集。Assembly
类提供了一个 GetTypes()
方法,可以检索该特定程序集中的所有类型。因此,您的代码可能如下所示:
foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (Type t in a.GetTypes())
{
// ... do something with 't' ...
}
}
带有检查程序集是否为动态的LINQ解决方案:
/// <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));
}
Linq简单易用:
IEnumerable<Type> types =
from a in AppDomain.CurrentDomain.GetAssemblies()
from t in a.GetTypes()
select t;
foreach(Type t in types)
{
...
}
通常你只关心从外部可见的程序集。因此,你需要调用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;
}
}
}
}
}