Nota che se hai un'interfaccia generica, IMyInterface<T>questo restituirà sempre false:
typeof(IMyInterface<>).IsAssignableFrom(typeof(MyType)) /* ALWAYS FALSE */
Questo non funziona neanche:
typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface<>)) /* ALWAYS FALSE */
Tuttavia, se MyTypeimplementa IMyInterface<MyType>questo funziona e restituisce true:
typeof(IMyInterface<MyType>).IsAssignableFrom(typeof(MyType))
Tuttavia, probabilmente non conoscerai il parametro type Tin fase di esecuzione . Una soluzione un po 'confusa è:
typeof(MyType).GetInterfaces()
.Any(x=>x.Name == typeof(IMyInterface<>).Name)
La soluzione di Jeff è un po 'meno complicata:
typeof(MyType).GetInterfaces()
.Any(i => i.IsGenericType
&& i.GetGenericTypeDefinition() == typeof(IMyInterface<>));
Ecco un metodo di estensione Typeche funziona in ogni 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);
}
}
(Nota che quanto sopra usa linq, che probabilmente è più lento di un ciclo.)
È quindi possibile fare:
typeof(MyType).IsImplementing(IMyInterface<>)