在类型上查找立即实现的接口

sdu*_*ooy 7 c# reflection

在以下场景中调用typeof(Bar).GetInterfaces()时,该方法返回IFoo和IBar.

interface IFoo {}
interface IBar : IFoo {}
class Bar : IBar {}

有没有办法让我只能在Bar上找到直接界面(IBar)?

Meh*_*ari 13

不,在编译的代码中没有"立即"接口这样的东西.您的课程有效编译为:

class Bar : IBar, IFoo { }
Run Code Online (Sandbox Code Playgroud)

你无法区分这两者.您唯一能做的就是检查所有这些接口,看看两个或多个接口是否相互继承(即使在这种情况下,您也无法真正检查该类的作者是否已明确提及代码中的基接口是不是):

static IEnumerable<Type> GetImmediateInterfaces(Type type)
{
    var interfaces = type.GetInterfaces();
    var result = new HashSet<Type>(interfaces);
    foreach (Type i in interfaces)
        result.ExceptWith(i.GetInterfaces());
    return result;
}
Run Code Online (Sandbox Code Playgroud)