Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting type arguments of generic interfaces that a class implements

I have a generic interface, say IGeneric. For a given type, I want to find the generic arguments which a class imlements via IGeneric.

It is more clear in this example:

Class MyClass : IGeneric<Employee>, IGeneric<Company>, IDontWantThis<EvilType> { ... }  Type t = typeof(MyClass); Type[] typeArgs = GetTypeArgsOfInterfacesOf(t);  // At this point, typeArgs must be equal to { typeof(Employee), typeof(Company) } 

What is the implementation of GetTypeArgsOfInterfacesOf(Type t)?

Note: It may be assumed that GetTypeArgsOfInterfacesOf method is written specifically for IGeneric.

Edit: Please note that I am specifically asking how to filter out IGeneric interface from all the interfaces that MyClass implements.

Related: Finding out if a type implements a generic interface

like image 436
Serhat Ozgel Avatar asked Jul 17 '09 08:07

Serhat Ozgel


People also ask

Which types can be used as arguments of a generic type?

The actual type arguments of a generic type are. reference types, wildcards, or. parameterized types (i.e. instantiations of other generic types).

Can a generic class implement an interface?

Only generic classes can implement generic interfaces. Normal classes can't implement generic interfaces.

What is a generic interface?

Generic Interfaces in Java are the interfaces that deal with abstract data types. Interface help in the independent manipulation of java collections from representation details. They are used to achieving multiple inheritance in java forming hierarchies. They differ from the java class.

How do you find the class object of a generic type?

Pass the class object instead and it's easy. The idea here is that since you can't extract the type parameter from the object, you have to do it the other way around: start with the class and then manipulate the object to match the type parameter.


1 Answers

To limit it to just a specific flavor of generic interface you need to get the generic type definition and compare to the "open" interface (IGeneric<> - note no "T" specified):

List<Type> genTypes = new List<Type>(); foreach(Type intType in t.GetInterfaces()) {     if(intType.IsGenericType && intType.GetGenericTypeDefinition()         == typeof(IGeneric<>)) {         genTypes.Add(intType.GetGenericArguments()[0]);     } } // now look at genTypes 

Or as LINQ query-syntax:

Type[] typeArgs = (     from iType in typeof(MyClass).GetInterfaces()     where iType.IsGenericType       && iType.GetGenericTypeDefinition() == typeof(IGeneric<>)     select iType.GetGenericArguments()[0]).ToArray(); 
like image 62
Marc Gravell Avatar answered Oct 09 '22 02:10

Marc Gravell