问题描述
在以下情况下调用的typeof(酒吧).GetInterfaces()方法返回的IFoo和伊巴尔。
When calling typeof(Bar).GetInterfaces() on the following scenario the method returns IFoo and IBar.
接口的IFoo {}结果
接口伊巴尔:的IFoo {}结果
级酒吧:伊巴尔{}
有没有办法,我可以在酒吧找到只顾眼前接口(IBAR)的方法吗?
Is there a way that I can find only the immediate interface (IBar) on Bar?
推荐答案
没有,有没有这样的东西作为编译代码的立竿见影的界面。你的类被有效地编译为:
No, there's no such thing as the "immediate" interface in the compiled code. Your class is effectively compiled as:
class Bar : IBar, IFoo { }
和不能区分这两者。你能做的唯一的事是检查所有这些,看看是否两个或两个以上的接口相互继承或没有(甚至在这种情况下,你不能真正检查类的作者是否明确提到的基本接口代码与否):
and you can't distinguish between the two. The only thing you could do is to check all of them and see whether two or more of the interfaces inherit from each other or not (and even in that case, you can't really check whether the author of the class has explicitly mentioned the base interface in code or not):
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;
}
这篇关于找到一个类型的直接实现的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!