IsAssignableFrom when an interface has generics, but not an implementation

I searched for this and found this: How to determine if a type is another common type

The problem with this solution is that it expects the implementation to have parameters of the same type. I want to see if the class implements an interface with any type parameter.

Example:

public interface IMapper<in TSource, out TDestination>
{ ... }

public class StringMapper : IMapper<string, StringBuilder>
{ ... }

Console.WriteLine(typeof(IMapper<,>).IsAssignableFrom(typeof(StringMapper)));

I want this to write true, but it writes false. How to check if a class implements an interface with common parameters?

+3
source share
2 answers

, GetInterfaces() StringMapper IsGenericType. , (IMapper<,>) , GetGenericTypeDefinition() , typeof(IMapper<,>).

. , , , . recursvly BaseType , BaseType .

+6

. , - :

    IEnumerable<Type> reports =
        from type in GetType().Assembly.GetTypes()
        where
            type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IReport<>)) &&
            type.IsClass
        select type;
+3

All Articles