How to get the type of the generic entity of the upper interface?

8

I have the following situation:

public class MinhaClasse : IMinhaClasse<Carro>
{
      //...
}
public static void Main(string[] args)
{
  var foo = new MinhaClasse();
}

Is it possible to get the generic parameter type of IMinhaClasse through my instance foo?

    
asked by anonymous 17.03.2014 / 19:52

1 answer

7

It is possible to know which type is using type reflection.

var tipos = foo.GetType()
    .GetInterfaces()
    .Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IMinhaClasse<>))
    .Select(x => x.GenericTypeArguments[0])
    .ToArray();

This will return an array with type Carro in the case of your example.

But suppose any type implements IMinhaClasse<Carro> and also IMinhaClasse<Bicicleta> , so the result will be an array containing Carro and Bicicleta .

EDIT

To get the declared parameters exactly on the type interfaces, not taking into account the inherited ones, then we will have to delete the inherited ones after picking all:

var fooType = foo.GetType();
var tipos = fooType
    .GetInterfaces()
    .Where(x => x.IsGenericType && x.GenericTypeArguments.Length == 1)
    .Select(x => x.GenericTypeArguments[0])
    .Except((fooType.BaseType ?? typeof(object)).GetInterfaces())
    .ToArray();

EDIT (2014 / MAR / 18) Just sharing my findings:

I've been researching the possibility of knowing which interfaces are implemented directly by a type, as declared in C # code , but I've come to the conclusion that this is not possible .

I'll explain with an example:

interface IIndireta { }

interface IDireta { }

class Base : IIndireta { }

class ClasseA : Base, IDireta { }

class ClasseB : Base, IDireta, IIndireta { }

The conclusion is as follows: can not differentiate how ClasseA and ClasseB implements their interfaces via code :

  • In the declaration of ClasseB the interface IIndireta is placed in the list of implementations, only this interface is also implemented by class Base , and it is not possible to know via reflection, IIndireta was declared directly or not.

  • In the declaration of ClasseA , the IIndireta interface is implemented by inheriting the Base class. However, through reflection, it is not possible to know that ClasseA does not have in its list of direct implementations the said interface.

17.03.2014 / 20:14