Consider a generic interface
public interface IA<T>
{
}
and two implementations
public class A1 : IA<string>
{}
public class A2 : IA<int>
{}
I want to write a method that finds the classes who implements IA interface with a specific type
public Type[] Find(IEnumerable<Type> types, Type type)
so that the following call
Find(new List<Type>{ typeof(A1), typeof(A2)}, typeof(string))
will return the type A1
IMPORTANT NOTE
I can assume that all the types passed in as the list will implement IA however not necessarily directly (For example A1 can inherit from BaseA that implements IA<string>)
How can I accomplish this through reflection?
Use MakeGenericType to construct a specific generic type and check if it is available in the list of interfaces which the given class implements.
private static Type FindImplementation(IEnumerable<Type> implementations, Type expectedTypeParameter)
{
Type genericIaType = typeof(IA<>).MakeGenericType(expectedTypeParameter);
return implementations.FirstOrDefault(x => x.GetInterfaces().Contains(genericIaType));
}
And you call it like this
Type type = FindImplementation(new []{ typeof(A1), typeof(A2)}, typeof(string));
//Returns A1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With