gpt4 book ai didi

c# - 搜索实现特定接口(interface)的类并执行方法

转载 作者:行者123 更新时间:2023-11-30 21:43:32 24 4
gpt4 key购买 nike

我想调用实现某个特定接口(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();
}

提前致谢

最佳答案

这里有两件事你必须做:

  • 找到实现接口(interface)的类型,以及
  • 实例化那些类型的对象

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

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

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

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

关于c# - 搜索实现特定接口(interface)的类并执行方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41649954/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com