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

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

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

有人知道如何用 C # 3.5做到这一点吗?

59332 次浏览

使用 Linq 的一个例子:

var types =
myAssembly.GetTypes()
.Where(m => m.IsClass && m.GetInterface("IMyInterface") != null);

您可以使用下面这样的内容,并根据您的需要进行调整。

var _interfaceType = typeof(ISomething);
var currentAssembly = System.Reflection.Assembly.GetExecutingAssembly();
var types = GetType().GetNestedTypes();


foreach (var type in types)
{
if (_interfaceType.IsAssignableFrom(type) && type.IsPublic && !type.IsInterface)
{
ISomething something = (ISomething)currentAssembly.CreateInstance(type.FullName, false);
something.TheMethod();
}
}

这段代码可以使用一些性能增强,但这只是一个开始。

一个工作代码示例:

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 的调用将成功。

您可以使用以下方法获取已加载程序集的列表:

Assembly assembly = System.Reflection.AppDomain.CurrentDomain.GetAssemblies()

从那里,您可以得到程序集中的类型列表(假设是公共类型) :

Type[] types = assembly.GetExportedTypes();

然后您可以通过在对象上找到该接口来询问每个类型是否支持该接口:

Type interfaceType = type.GetInterface("ISomething");

不确定是否有更有效的反射方法。

foreach (Type t in Assembly.GetCallingAssembly().GetTypes())
{
if (t.GetInterface("ITheInterface") != null)
{
ITheInterface executor = Activator.CreateInstance(t) as ITheInterface;
executor.PerformSomething();
}
}

也许我们应该走这边

foreach ( var instance in Assembly.GetExecutingAssembly().GetTypes().Where(a => a.GetConstructor(Type.EmptyTypes) != null).Select(Activator.CreateInstance).OfType<ISomething>() )
instance.Execute();