How to get the generic type entity type from the top interface?

Asked

Viewed 492 times

8

I have the following situation:

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

It is possible to get the generic parameter type of Iminhaclass through my foo instance?

1 answer

7


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

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 the type Carro in the case of your example.

But suppose some guy implements IMinhaClasse<Carro> and also IMinhaClasse<Bicicleta>, then the result will be an array containing Carro and Bicicleta.

EDIT

To take the parameters declared exactly in the type interfaces, without considering the inherited ones, then we will have to eliminate the inherited ones after taking 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 have been researching the possibility of knowing which interfaces are implemented directly by a type, as declared in code C#, but I have come to the conclusion that this is not possible.

I will 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:: it is not possible to differentiate the way in which the ClasseA and the ClasseB implement their interfaces via code:

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

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

  • I got the result I wanted, but you would know some way to get the result without specifying the type (typeof<>))?

  • Yes you can, but in this case you will also take the types of interfaces as IEnumerable<xxx> or any other generic, which may have nothing to do... that’s right?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.