搜索实现特定接口的类并执行方法

时间:2017-01-14 12:25:02

标签: c# class methods interface

我想调用实现某些特定接口的类中的方法。

我经常尝试和搜索但无法知道该怎么做。 这是我的理想,但它不起作用。

希望有人可以帮助我。

// getting the list
List<Type> instances =
    Assembly.GetExecutingAssembly()
        .GetTypes()
        .Where(a => a.GetInterfaces().Contains(typeof(ISearchThisInterface))).ToList();

foreach (Type instance in instances)
{
  // here I want to execute the method of the classes that implement the interface
  (instance as ISearchThisInterface).GetMyMethod(); 
}

非常感谢提前

1 个答案:

答案 0 :(得分:3)

你需要做两件事:

  • 查找实现界面的类型,
  • 实例化这些类型的对象

只有在两者完成后才能在实例上调用方法。

另一个重要方面是所有选择的类型必须允许实例化:它们必须是非抽象类型,非泛型类型,并且具有无参数构造函数,否则您将无法实例化它们。

如果您知道必须创建该类型的新实例,那么这是一种可能的方式:

IEnumerable<ISearchThisInterface> instances =
    Assembly.GetExecutingAssembly()
        .GetTypes()  // Gets all types
        .Where(type => typeof(ISearchThisInterface).IsAssignableFrom(type)) // Ensures that object can be cast to interface
        .Where(type => 
            !type.IsAbstract && 
            !type.IsGenericType &&
            type.GetConstructor(new Type[0]) != null) // Ensures that type can be instantiated
        .Select(type => (ISearchThisInterface)Activator.CreateInstance(type)) // Create instances
        .ToList();

foreach (ISearchThisInterface instance in instances)
{
    instance.AMethod();
}