如何找到它实现指定接口的所有类? [英] 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?
推荐答案
一个工作code-示例:
A working code-sample:
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屋!