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

时间:2015-11-13 14:26:59

标签: c# generics reflection

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

举一个具体的例子:

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

现在,我想扫描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;
}

非常感谢一些帮助!

1 个答案:

答案 0 :(得分:4)

这种情况不正确:

x.IsAssignableFrom(typeof(ICanHandleIntent<>))

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

你想要的是

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

检查type参数也是错误的。它应该是

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

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

相关问题