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 their respective T types from the Foo interface - SomeClass for FinalClass1 and SomeOtherClass for FinalClass2. The abstract classes can implement more generic interfaces, but always only one Foo.
How can I achieve this, using reflection?
How can I also ensure that the type is implementing Foo regardless of what type the T is? Something like
bool bIsFoo = typeof(SomeType).IsAssignableFrom(Foo<>)
The above doesn't work.
Java Generic Classes and Subtyping We can subtype a generic class or interface by extending or implementing it. The relationship between the type parameters of one class or interface and the type parameters of another are determined by the extends and implements clauses.
You can't inherit from a Generic type argument. C# is strictly typed language. All types and inheritance hierarchy must be known at compile time. . Net generics are way different from C++ templates.
Declaring Variant Generic Interfaces You can declare variant generic interfaces by using the in and out keywords for generic type parameters. ref , in , and out parameters in C# cannot be variant. Value types also do not support variance. You can declare a generic type parameter covariant by using the out keyword.
Interface Type Constraint You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter.
Search type interfaces for generic interface which is Foo<>
. Then get first generic argument of that interface:
type.GetInterfaces()
.FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(Foo<>))
?.GetGenericArguments().First();
If you want to check whether type is implementing Foo<>
:
type.GetInterfaces()
.Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(Foo<>))
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