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

Mar*_*tin 66 c# reflection

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

我希望CClass找到所有的实现ISomething,实例化它的实例并执行该方法.

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

Mat*_*ton 130

一个有效的代码示例:

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
}
Run Code Online (Sandbox Code Playgroud)

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

  • nevermind .. var instances = from assembly in AppDomain.CurrentDomain.GetAssemblies()from t in assembly.GetTypes()where t.GetInterfaces().Contains(typeof(ISomething))&& t.GetConstructor(Type.EmptyTypes)!= null选择Activator.CreateInstance(t)作为ISomething; (13认同)
  • 微小的清理建议 - 使用Type.EmptyTypes而不是实例化一个新的空Type数组. (9认同)

Mit*_*nny 10

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

Assembly assembly = System.Reflection.AppDomain.CurrentDomain.GetAssemblies()
Run Code Online (Sandbox Code Playgroud)

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

Type[] types = assembly.GetExportedTypes();
Run Code Online (Sandbox Code Playgroud)

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

Type interfaceType = type.GetInterface("ISomething");
Run Code Online (Sandbox Code Playgroud)

不确定是否有更有效的方法来做反射.


CMS*_*CMS 8

使用Linq的一个例子:

var types =
  myAssembly.GetTypes()
            .Where(m => m.IsClass && m.GetInterface("IMyInterface") != null);
Run Code Online (Sandbox Code Playgroud)