我有一些代码来加载程序集并获取所有类型,它们实现了某个接口,就像这样(假设 asm 是一个有效且已加载的程序集)。
var results = from type in asm.GetTypes()
where typeof(IServiceJob).IsAssignableFrom(type)
select type;
现在我被困住了:我需要创建这些对象的实例并调用对象的方法和属性。而且我需要将创建的对象的引用存储在一个数组中以供以后使用。
我有一些代码来加载程序集并获取所有类型,它们实现了某个接口,就像这样(假设 asm 是一个有效且已加载的程序集)。
var results = from type in asm.GetTypes()
where typeof(IServiceJob).IsAssignableFrom(type)
select type;
现在我被困住了:我需要创建这些对象的实例并调用对象的方法和属性。而且我需要将创建的对象的引用存储在一个数组中以供以后使用。
哦,哇——我几天前才在博客上写过这个。这是我返回实现给定接口的所有类型的实例的方法:
private static IEnumerable<T> InstancesOf<T>() where T : class
{
var type = typeof(T);
return from t in type.Assembly.GetExportedTypes()
where t.IsClass
&& type.IsAssignableFrom(t)
&& t.GetConstructor(new Type[0]) != null
select (T)Activator.CreateInstance(t);
}
如果您将其重构为接受程序集参数而不是使用接口的程序集,它就会变得足够灵活以满足您的需要。
您可以使用以下方法创建类型的实例Activator.CreateInstance
:-
IServiceJob x = Activator.CreateInstance(type);
所以你的代码变成: -
IServiceJob[] results = (from type in asm.GetTypes()
where typeof(IServiceJob).IsAssignableFrom(type)
select (IServiceJob)Activator.CreateInstance(type)).ToArray();
(注意将 var 更改为 IServiceJob[] 以明确创建的内容)。