c# - 查找实现具有特定 T 类型的特定通用接口(interface)的所有类型

标签 c# generics reflection

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

举个具体的例子:

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;
}

一些帮助将不胜感激!

最佳答案

这个条件不正确:

x.IsAssignableFrom(typeof(ICanHandleIntent<>))

实现通用接口(interface)实例的类型不能从通用接口(interface)定义本身分配,ICanHandleIntent<>代表。

你想要的是

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

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

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

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

关于c# - 查找实现具有特定 T 类型的特定通用接口(interface)的所有类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33694960/

相关文章:

c# - 仅获取日期时间对象的时间

c# - 在单元测试中将 DI 与没有依赖关系的模块/类一起使用是否有令人信服的理由?

php - 有没有办法访问给定对象的所有引用?

Java:如何在编译时找到方法的调用者?

c# - 在 C#/.NET 2.0 中控制双缓冲所有者绘制的 UserControl 的设计器外观

c# - 在 C#/.NET 中合并两个图像

c# - 如何在 C# 中捕获通用异常的所有变体

java - 为什么 instanceof 运算符允许在无界通配符类型上使用,而在 Java 中的其他参数化类型上却不允许?

generics - 无法定义运算符

java - 看到 InvokingTargetException 异常