小编典典

如何找到实现给定接口的所有类?

c#

在给定的名称空间下,我有一组实现接口的类。叫它ISomething。我有另一个类(我们称之为CClass),它知道ISomething但不知道实现该接口的类。

我希望CClass查找的所有实现ISomething,实例化它的一个实例并执行该方法。

有人对使用C#3.5做到这一点有想法吗?


阅读 325

收藏
2020-05-19

共1个答案

小编典典

工作代码示例:

var instances = from t in Assembly.GetExecutingAssembly().GetTypes()
                where t.GetInterfaces().Contains(typeof(ISomething))
                         && t.GetConstructor(Type.EmptyTypes) != null
                select Activator.CreateInstance(t) as ISomething;

foreach (var instance in instances)
{
    instance.Foo(); // where Foo is a method of ISomething
}

编辑 添加了对无参数构造函数的检查,以便对CreateInstance的调用将成功。

2020-05-19