我有一些代码来加载程序集并获取所有类型,这些类型实现了某个接口,就像这样(假设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 []以清除正在创建的内容。)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top