【问题标题】:Search for classes that implement specific interface and execute a method搜索实现特定接口并执行方法的类
【发布时间】:2017-05-29 17:32:53
【问题描述】:

我想调用一个方法,该方法在实现某些特定接口的类中。

我已经尝试并搜索了很多,但无法弄清楚该怎么做。 这是我的想法,但它不起作用。

希望有人可以帮助我。

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

在此先感谢

【问题讨论】:

    标签: c# class methods interface


    【解决方案1】:

    你必须在这里做两件事:

    • 找到实现接口的类型,然后
    • 实例化这些类型的对象

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

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

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

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

    【讨论】:

    • 看起来不错。不幸的是我会得到一个异常,因为类的构造函数不是空的。但是我有不同的类和不同的构造函数。有没有办法动态解决这个问题? //这里是一个示例 public class SomeClass : ISomeClass, ISearchThisInterface { protected readonly IBeAnotherInterface _anotherService;公共 SomeClass (IBeAnotherInterface anotherService) { _anotherService = anotherService); } //这里有两个接口的一些方法 }
    • 可以使用 IoC 容器来解决这个问题,然后动态解析类型。这将是比上述解决方案更重的解决方案,您可以尝试谷歌(例如stackoverflow.com/questions/820520/…)。基于Activator 的解决方案仅适用于无参数构造函数。
    • 如果您想尝试使用 IoC 容器将此解决方案提升到一个新的水平,那么最好打开一个新问题并发布适用于无参数构造函数的最终代码作为开始观点。有人可能会很快提供帮助。
    • 非常感谢,我去看看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 2019-04-07
    • 1970-01-01
    • 2014-07-28
    • 2018-05-26
    相关资源
    最近更新 更多