查找实现具有特定 T 类型的特定通用接口的所有类型

Find all types implementing a certain generic interface with specific T type

我有几个 类 继承自 abstract class BrowsingGoal。其中一些实现了一个名为 ICanHandleIntent<TPageIntent> where TPageIntent: PageIntent 的接口。

举个具体的例子:

public class Authenticate : BrowsingGoal, ICanHandleIntent<AuthenticationNeededIntent>
{
    ...
}

现在我想扫描 CurrentDomain 的程序集,以查找使用 AuthenticationNeededIntent 实现 ICanHandleIntent 的所有类型。这是我目前所拥有的,但似乎没有找到任何东西:

protected BrowsingGoal FindNextGoal(PageIntent intent)
{
    // Find a goal that implements an ICanHandleIntent<specific PageIntent>
    var goalHandler = AppDomain.CurrentDomain
        .GetAssemblies()
        .SelectMany(assembly => assembly.GetTypes())
        .FirstOrDefault(t => t.IsAssignableFrom((typeof (BrowsingGoal))) &&
                                t.GetInterfaces().Any(x =>
                                    x.IsGenericType &&
                                    x.IsAssignableFrom(typeof (ICanHandleIntent<>)) &&
                                    x.GetGenericTypeDefinition() == intent.GetType()));

    if (goalHandler != null)
        return Activator.CreateInstance(goalHandler) as BrowsingGoal;
}

非常感谢您的帮助!

这个条件不正确:

x.IsAssignableFrom(typeof(ICanHandleIntent<>))

无法从 ICanHandleIntent<> 表示的通用接口定义本身分配实现通用接口实例的类型。

你想要的是

x.GetGenericTypeDefinition() == typeof(ICanHandleIntent<>)

类型参数的检查也是错误的。应该是

x.GetGenericArguments()[0] == intent.GetType()

因为您要查找类型参数,即通用名称后三角括号中的类型。