【问题标题】:find type implementing generic interface through reflection通过反射找到实现泛型接口的类型
【发布时间】:2015-03-29 13:22:23
【问题描述】:

考虑一个通用接口

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可以从实现BaseABaseA继承)

我怎样才能通过反思来做到这一点?

【问题讨论】:

    标签: c# reflection


    【解决方案1】:

    使用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 对我来说确实是缺失的部分。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多