【问题标题】:Find all types implementing a certain generic interface with specific T type查找实现具有特定 T 类型的某个通用接口的所有类型
【发布时间】:2016-02-15 03:58:24
【问题描述】:

我有几个继承自 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;
}

我们将不胜感激!

【问题讨论】:

  • .FirstOrDefault 删除它,因为它只分析第一种类型。将其替换为.Where。如果您只想要第一个结果,请在语句末尾添加FirstOrDefault()。
  • @SteffenWinkler 不正确,FirstOrDefault(),当提供谓词参数时,循环遍历集合并返回计算结果为 true 的第一个实例。

标签: c# generics reflection


【解决方案1】:

这个条件不正确:

x.IsAssignableFrom(typeof(ICanHandleIntent<>))

实现泛型接口实例的类型不能从泛型接口定义本身分配,ICanHandleIntent&lt;&gt; 表示。

你想要的是

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多