从实现特定接口的程序集中获取 类

Get classes from assembly that implement a specific interface

我有这样的界面:

public interface IMyInterface<T>
{
    void MyMethod(T obj);
}

我正在尝试查找程序集是否有任何 类 实现此功能。我找到了一些示例,但它们都演示了检查没有 T 的简单接口的实现。

这是我写的:

var interfaceType = typeof(IMyInterface<>);
Assembly assembly = Assembly.LoadFrom(assemblyFile);
var allTypes = assembly.GetTypes();
foreach(Type type in allTypes)
{
     var isImplementing = interfaceType.IsAssignableFrom(type);
}

我也试过这样做:

var interfaces = type.GetInterfaces();
var isImplementing = interfaces.Contains(interfaceType);

isImplementing 始终为 false。

第二种方法你差不多搞定了。然而,type.GetInterfaces() 返回的接口类型将是特定类型的实现,例如IMyInterface<String>。因此,您必须根据 GenericTypeDefinition 检查您的接口类型。

试试这个:

var interfaces = type.GetInterfaces();
var isImplementing = interfaces.Where(i => i.IsGenericType).Any(i => i.GetGenericTypeDefinition() == interfaceType);

I'm trying to find if an assembly has any classes that implement this.

对于您的示例,您需要 'assemblyFile'。 看看这个例子,我曾经使用 CurentDomain (System.AppDomain.CurrentDomain):

获取所有实现 IMyInterface 的 类
public IEnumerable<IMyInterface> GetClasses(AppDomain CurrentDomain)
    {
        var _type = typeof(IMyInterface);

        var _types = CurrentDomain.GetAssemblies().SelectMany(_s => _s.GetTypes()).Where(i => _type.IsAssignableFrom(i) && !i.IsInterface);

        List<IMyInterface> _classes = new List<IMyInterface>();

        foreach (var _instance in _types)
        {
            _classes.Add((IMyInterface)Activator.CreateInstance(_instance));
        }

        return _classes;
    }

*还要注意 '!i.IsInterface' 使用它不会 return 包含接口

的程序集

我希望这能帮助您解决问题。