Para abordar completamente el sistema de tipos, creo que debe manejar la recursividad, p. IList<T>
: ICollection<T>
: IEnumerable<T>
, sin el cual no sabría que IList<int>
finalmente implementa IEnumerable<>
.respuesta
/// <summary>Determines whether a type, like IList<int>, implements an open generic interface, like
/// IEnumerable<>. Note that this only checks against *interfaces*.</summary>
/// <param name="candidateType">The type to check.</param>
/// <param name="openGenericInterfaceType">The open generic type which it may impelement</param>
/// <returns>Whether the candidate type implements the open interface.</returns>
public static bool ImplementsOpenGenericInterface(this Type candidateType, Type openGenericInterfaceType)
{
Contract.Requires(candidateType != null);
Contract.Requires(openGenericInterfaceType != null);
return
candidateType.Equals(openGenericInterfaceType) ||
(candidateType.IsGenericType && candidateType.GetGenericTypeDefinition().Equals(openGenericInterfaceType)) ||
candidateType.GetInterfaces().Any(i => i.IsGenericType && i.ImplementsOpenGenericInterface(openGenericInterfaceType));
}
¡Esta es una solución muy elegante! Los otros que he visto en SO usan bucles foreach o consultas LINQ más largas. Sin embargo, tenga en cuenta que para usar esto, necesita tener .NET framework 3.5. –
Te recomiendo que hagas de este un método de extensión a la http://bit.ly/ccza8B - ¡lo limpiarás bastante bien! –
Dependiendo de sus necesidades, es posible que deba recurrir en las interfaces devueltas. –