如何找到实现给定接口的所有类? [英] How to find all the classes which implement a given interface?
问题描述
在给定的命名空间下,我有一组实现接口的类.我们称之为ISomething
.我有另一个类(我们称之为 CClass
),它知道 ISomething
但不知道实现该接口的类.
Under a given namespace, I have a set of classes which implement an interface. Let's call it ISomething
. I have another class (let's call it CClass
) which knows about ISomething
but doesn't know about the classes which implement that interface.
我希望 CClass
查找 ISomething
的所有实现,实例化它的一个实例并执行该方法.
I would like that CClass
to look for all the implementation of ISomething
, instantiate an instance of it and execute the method.
有人知道如何使用 C# 3.5 做到这一点吗?
Does anybody have an idea on how to do that with C# 3.5?
推荐答案
工作代码示例:
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 的调用成功.
Edit Added a check for a parameterless constructor so that the call to CreateInstance will succeed.
这篇关于如何找到实现给定接口的所有类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!