lundi 28 mai 2018

Reflection to get if class has an interface that "implements" another interface

I'm currently trying to achieve the following:

I have a interface this interface:

public interface IRepository<TEntity>
{
   //Some Methods
}

Then I have another interface that extends the one above:

public interface IAttractionRepository : IRepository<Attraction>
{
   //More methods
}

Finally, I have an implementation (that also implements other interfaces):

public class AttractionRepository : ISomethingElse, IAnotherSomethingElse, IAttractionRepository
{
  //Implementations and methods
}

What I am trying to achieve is: Provided type AttractionRepository, I want to search it's interfaces and get which one is extending the intercface IRepository.

My code is as follows:

Type[] interfaces = typeof(AttractionRepository).GetInterfaces(); //I get three interfaces here, which is fine.
Type iface = null;

foreach (Type t in interfaces) //Iterate through all interfaces
    foreach(Type t1 in t.GetInterfaces()) //For each of the interfaces an interface is extending, I want to know if there's any interface that is "IRepository<Attraction>"
        if (t1.IsSubclassOf(typeof(IRepository<>).MakeGenericType(typeof(Attraction)))) //Always false
            iface = t;

I have tried several other solutions but with no success.





Aucun commentaire:

Enregistrer un commentaire