mercredi 16 décembre 2020

How can I check whether `SomeType<>` implements `IEnumerable<>`?

I have an open generic type definition and want to check whether this open definition implements an open interface definition.

static bool IsOpenGenericTypeImplementing(this Type candidate, Type iface) => 
   candidate.IsGenericTypeDefinition && 
   candidate.GetGenericArguments().Length == 1 && 
   candidate.MakeGenericType(typeof(object)).IsAssignableTo(iface.MakeGenericType(typeof(object)));  // does not work

// example call will work:
var result = typeof(List<>).IsOpenGenericTypeImplementing(typeof(IEnumerable<>)); 

// following test will fail (exception)
class SomeType<T> where T : Enum, IEnumerable<T>
{
}

[Fact]
void CheckSomeType()
{
    Assert.True(typeof(SomeType<>).IsOpenGenericTypeImplementing(typeof(IEnumerable<>)));
}

The problem with the approach above is that is will fail if there are type constraints.

I found some similar questions but all seem to need a closed generic type definition (List<T>). E.g. Finding out if a type implements a generic interface





Aucun commentaire:

Enregistrer un commentaire