搜索实现特定接口并执行方法的类 [英] Search for classes that implement specific interface and execute a method

查看:45
本文介绍了搜索实现特定接口并执行方法的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to call a method that is in classes that implement some specific interface.

我已经尝试和搜索了很多,但是却找不到解决方法.这是我的主意,但是没有用.

I have tried and searched a lot but can't get out what to do. This is my idear about but it is not working.

希望有人可以帮助我.

// 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(); 
}

非常感谢

推荐答案

在这里您需要做两件事:

There are two things you have to do here:

  • 查找实现该接口的类型,并且
  • 实例化这些类型的对象

只有在完成这两项之后,您才能在实例上调用方法.

Only after both are done can you invoke a method on instances.

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

Another important aspect is that all types selected must allow instantiation: they must be non-abstract types, non-generic types, and have parameterless constructor, or otherwise you won't have the way to instantiate them.

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

If you are aware that you have to create new instances of the type, then this is one possible way:

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();
}

这篇关于搜索实现特定接口并执行方法的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆