繁体   English   中英

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

[英]How to find all the classes which implement a given interface?

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

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

有没有人知道如何用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的调用成功。

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

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

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

Type[] types = assembly.GetExportedTypes();

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

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

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

使用Linq的一个例子:

var types =
  myAssembly.GetTypes()
            .Where(m => m.IsClass && m.GetInterface("IMyInterface") != null);
foreach (Type t in Assembly.GetCallingAssembly().GetTypes())
{
    if (t.GetInterface("ITheInterface") != null)
    {
        ITheInterface executor = Activator.CreateInstance(t) as ITheInterface;
        executor.PerformSomething();
    }
}

您可以使用以下内容并根据您的需要进行定制。

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();
    }
}

此代码可以使用一些性能增强,但它是一个开始。

也许我们应该这样做

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM