通过反射找到实现通用接口的类型
find type implementing generic interface through reflection
考虑通用接口
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))
将return类型A1
重要提示
我可以假设作为列表传入的所有类型都将实现 IA
但是 不一定直接(例如 A1
可以继承自 BaseA
实现 IA<string>
)
我怎样才能通过反思完成这个?
使用 MakeGenericType
构造特定泛型类型并检查它是否在给定 class 实现的接口列表中可用。
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
考虑通用接口
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))
将return类型A1
重要提示
我可以假设作为列表传入的所有类型都将实现 IA
但是 不一定直接(例如 A1
可以继承自 BaseA
实现 IA<string>
)
我怎样才能通过反思完成这个?
使用 MakeGenericType
构造特定泛型类型并检查它是否在给定 class 实现的接口列表中可用。
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