Tenga en cuenta que si tiene una interfaz genérica IMyInterface<T>, esto siempre devolverá false:
typeof(IMyInterface<>).IsAssignableFrom(typeof(MyType)) /* ALWAYS FALSE */
Esto tampoco funciona:
typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface<>)) /* ALWAYS FALSE */
Sin embargo, si MyTypeimplementa IMyInterface<MyType>esto funciona y devuelve true:
typeof(IMyInterface<MyType>).IsAssignableFrom(typeof(MyType))
Sin embargo, es probable que no conozca el parámetro de tipo Ten tiempo de ejecución . Una solución algo hacky es:
typeof(MyType).GetInterfaces()
.Any(x=>x.Name == typeof(IMyInterface<>).Name)
La solución de Jeff es un poco menos hacky:
typeof(MyType).GetInterfaces()
.Any(i => i.IsGenericType
&& i.GetGenericTypeDefinition() == typeof(IMyInterface<>));
Aquí hay un método de extensión Typeque funciona para cualquier caso:
public static class TypeExtensions
{
public static bool IsImplementing(this Type type, Type someInterface)
{
return type.GetInterfaces()
.Any(i => i == someInterface
|| i.IsGenericType
&& i.GetGenericTypeDefinition() == someInterface);
}
}
(Tenga en cuenta que lo anterior usa linq, que probablemente es más lento que un bucle).
Entonces puedes hacer:
typeof(MyType).IsImplementing(IMyInterface<>)