1

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

我有一个接口这个接口:

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;

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

4

1 回答 1

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);
}

问题是没有内置函数,因为您要查找的接口是通用接口。

在您的特定情况下,您会像这样使用它:

Type implementingInterface = typeof(AttractionRepository).GetInterfaces().Where(i => i.ImplementsInterface(typeof(IRepository<>))).FirstOrDefault();
于 2018-05-28T14:43:41.663 回答