簡體   English   中英

通過反射找到實現通用接口的類型

[英]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))

將返回類型A1

重要的提示

我可以假定作為列表傳入的所有類型都將實現IA 不一定直接實現(例如A1可以從實現IA<string> BaseA繼承)

我該如何通過反思做到這一點?

使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM