Generic type from base interface

My class structure (simplified)

interface Foo<T> { } abstract class Bar1 : Foo<SomeClass> { } abstract class Bar2 : Foo<SomeOtherClass> { } class FinalClass1 : Bar1 { } class FinalClass2 : Bar2 { } 

Now, having only the type FinalClass1 and FinalClass2, I need to get the corresponding T-types from the Foo interface - SomeClass for FinalClass1 and SomeOtherClass for FinalClass2. Abstract classes can implement more general interfaces, but there is always only one Foo.

  • How can I achieve this using reflection?

  • How can I also ensure that a type implements Foo regardless of type T? Sort of

bool bIsFoo = typeof(SomeType).IsAssignableFrom(Foo<>)

The above does not work.

+5
source share
1 answer

Search type interfaces for the general Foo<> interface. Then get the first general argument of this interface:

 type.GetInterfaces() .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(Foo<>)) ?.GetGenericArguments().First(); 

If you want to check if type Foo<> implements:

 type.GetInterfaces() .Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(Foo<>)) 
+4
source

Source: https://habr.com/ru/post/1263876/


All Articles