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

Pet*_*ter 2 c# generics reflection

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

举个具体的例子:

public class Authenticate : BrowsingGoal, ICanHandleIntent<AuthenticationNeededIntent>
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

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

一些帮助将不胜感激!

das*_*ght 7

此条件不正确:

x.IsAssignableFrom(typeof(ICanHandleIntent<>))
Run Code Online (Sandbox Code Playgroud)

实现泛型接口实例的类型不能从泛型接口定义本身分配,它ICanHandleIntent<>表示。

你想要的是

x.GetGenericTypeDefinition() == typeof(ICanHandleIntent<>)
Run Code Online (Sandbox Code Playgroud)

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

x.GetGenericArguments()[0] == intent.GetType()
Run Code Online (Sandbox Code Playgroud)

因为您正在寻找类型参数,即泛型名称后面三角括号中的类型。