繁体   English   中英

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

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

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

举一个具体的例子:

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

现在,我想扫描CurrentDomain的程序集,以ICanHandleIntent使用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<>)

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM