通过反射查找实现通用接口的类型

3
考虑一个通用接口
public interface IA<T>
{
}

以及两种实现方式。

public class A1 : IA<string>
{}
public class A2 : IA<int>
{}

我想编写一个方法,找到实现了特定类型IA接口的类。
public Type[] Find(IEnumerable<Type> types, Type type)

以便进行以下调用

Find(new List<Type>{ typeof(A1), typeof(A2)}, typeof(string))

将返回类型A1

重要提示

我可以假设作为列表传递的所有类型都将实现IA,但不一定是直接实现(例如A1可以继承实现IA<string>BaseA

如何通过反射实现这一点?

1个回答

4

使用MakeGenericType构造特定的泛型类型,并检查它是否在给定类实现的接口列表中可用。

private static Type FindImplementation(IEnumerable<Type> implementations, Type expectedTypeParameter)
{
    Type genericIaType = typeof(IA<>).MakeGenericType(expectedTypeParameter);

    return implementations.FirstOrDefault(x => x.GetInterfaces().Contains(genericIaType));
}

你可以这样调用它

Type type = FindImplementation(new []{ typeof(A1), typeof(A2)}, typeof(string));
//Returns A1

MakeGenericType 对我来说确实是缺失的一块。谢谢! - Omri Btian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接