How can I get base interface of an interface by reflection? I have tried to call BaseType propery, but value of It is null. After that I need to find generic type class of interface.
I need to find Foo
type from the type of ISomeInterfaceForItem
on this sample.
Type oType = typeof(ISomeInterfaceForItem);
Type oBase = oType.BaseType; // equals null
public interface ISomeInterfaceForItem: ISomeInterface<Foo>
{
}
public interface ISomeInterface<T>
{
}
Interfaces do not participate in inheritance, so BaseType
makes no sense. Instead, you need to see what kinds of interfaces are implemented by the given type:
oType
.FindInterfaces((t, _) => t.IsGenericType && t.GetGenericTypeDefinition()
== typeof(ISomeInterface<>), null)
.Select(i => i.GetGenericArguments().First())
Note that one class can implement multiple variants of ISomeInterface<>
- e.g. class MyClass : ISomeInterface<Foo>, ISomeInterface<Bar>
- that's why the result of the sample above is an enumerable of types, rather than just a single type.
You can get the inherited interfaces using GetInterface()
and enumerate the generic arguments using GetGenericArguments()
:
Type generic = typeof(I2).GetInterface("ISomeInterfaceForItem`1")?.
GetGenericArguments().FirstOrDefault();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With