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

本文关键字:类型 接口 实现 查找 | 更新日期: 2023-09-27 18:21:52

我有几个从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;
}

如果能提供帮助,我们将不胜感激!

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

此条件不正确:

x.IsAssignableFrom(typeof(ICanHandleIntent<>))

实现泛型接口实例的类型不能从ICanHandleIntent<>表示的泛型接口定义本身进行赋值。

你想要的是

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

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

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

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