在以下场景中调用typeof(Bar).GetInterfaces()时,该方法返回IFoo和IBar.
接口IFoo {}
接口IBar:IFoo {}
class Bar:IBar {}
有没有办法可以在Bar上找到直接界面(IBar)?
解决方法
不,在编译的代码中没有“立即”接口这样的东西.您的课程有效编译为:
- class Bar : IBar,IFoo { }
你无法区分这两者.您唯一能做的就是检查所有这些接口,看看两个或多个接口是否相互继承(即使在这种情况下,您也无法真正检查该类的作者是否已明确提及代码中的基接口是不是):
- 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;
- }