如果类具有“实现”另一个接口

时间:2018-05-28 14:31:24

标签: c# reflection

我目前正在努力实现以下目标:

我有一个界面这个界面:

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

然后我有另一个扩展上面的界面:

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

最后,我有一个实现(也实现了其他接口):

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

我想要实现的是:提供类型AttractionRepository,我想搜索它的接口并获取哪个扩展接口IRepository。

我的代码如下:

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;

我尝试了其他几种解决方案但没有成功。

1 个答案:

答案 0 :(得分:1)

对于这种情况,这样的事情非常方便:

/// <summary>
/// Returns whether or not the specified class or interface type implements the specified interface.
/// </summary>
/// <param name="implementor">The class or interface that might implement the interface.</param>
/// <param name="interfaceType">The interface to look for.</param>
/// <returns><b>true</b> if the interface is supported, <b>false</b> if it is not.</returns>
public static bool ImplementsInterface(this Type implementor, Type interfaceType)
{
    if (interfaceType.IsGenericTypeDefinition)
    {
        return (implementor.IsGenericType && implementor.GetGenericTypeDefinition() == interfaceType) ||
            (implementor.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == interfaceType));
    }
    else return interfaceType.IsAssignableFrom(implementor);
}

问题在于,由于您正在寻找的界面是通用界面,因此没有内置功能。<​​/ p>

在您的具体情况下,您可以使用以下内容:

Type implementingInterface = typeof(AttractionRepository).GetInterfaces().Where(i => i.ImplementsInterface(typeof(IRepository<>))).FirstOrDefault();