Bri*_*ins 59 .net c# asp.net reflection types
我需要在网站或Windows应用程序中的所有程序集中查找特定类型,是否有一种简单的方法可以执行此操作?就像ASP.NET MVC的控制器工厂如何查看控制器的所有程序集一样.
谢谢.
Ond*_*cny 98
有两个步骤来实现这一目标:
AppDomain.CurrentDomain.GetAssemblies()让你在当前的应用程序域中加载的所有程序集.Assembly类提供了一个GetTypes()到该特定组件内检索所有类型的方法.因此,您的代码可能如下所示:
foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (Type t in a.GetTypes())
{
// ... do something with 't' ...
}
}
Run Code Online (Sandbox Code Playgroud)
要查找特定类型(例如,实现给定的接口,继承共同的祖先或其他任何东西),您必须过滤掉结果.如果您需要在应用程序的多个位置执行此操作,建立一个提供不同选项的帮助程序类是个好主意.例如,我通常应用名称空间前缀过滤器,接口实现过滤器和继承过滤器.
Tho*_*que 29
使用Linq很容易:
IEnumerable<Type> types =
from a in AppDomain.CurrentDomain.GetAssemblies()
from t in a.GetTypes()
select t;
foreach(Type t in types)
{
...
}
Run Code Online (Sandbox Code Playgroud)
mhe*_*man 29
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));
}
Run Code Online (Sandbox Code Playgroud)
最常见的是,您只对从外部可见的组件感兴趣.因此,您需要调用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;
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48142 次 |
| 最近记录: |