确定类是否实现了非常特定的接口

Jef*_*fim 11 c# reflection inheritance interface

关于这个主题有很多问题,但我的版本略有改动.

我们有以下代码:

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

bool Implements_IFoo(Type type) { /* ??? */ }
Run Code Online (Sandbox Code Playgroud)

现在,故事的转折:Implements_IFoo当Type仅实现IFoo而不是从IFoo派生的任何接口时,该方法应该只返回true.这里举例说明此方法的一些示例:

Implements_IFoo(typeof(Foo)); // Should return true

Implements_IFoo(typeof(Bar)); // Should return false as Bar type 
                              // implements an interface derived from IFoo
Run Code Online (Sandbox Code Playgroud)

请注意,可能有许多从IFoo派生的接口,您不一定知道它们的存在.

显而易见的方法是通过反射找到从IFoo派生的所有接口,然后只检查typeof(Bar).GetInterfaces()就是那里存在的任何一个.但我想知道是否有人可以提出更优雅的解决方案.

PS问题源于我发现的一些代码,它们使用了对class(if(obj.GetType() == typeof(BaseClass)) { ... })的检查.我们正在用特定代码的接口替换类.另外,以防万一 - 我将此检查作为布尔标志实现,所以这个问题纯粹是假设的.

Bot*_*000 9

我试过了,因为它听起来很有趣,这适用于你的例子:

bool ImplementsIFooDirectly(Type t) {
    if (t.BaseType != null && ImplementsIFooDirectly(t.BaseType)) { 
        return false; 
    }
    foreach (var intf in t.GetInterfaces()) {
        if (ImplementsIFooDirectly(intf)) { 
            return false;
        }
    }
    return t.GetInterfaces().Any(i => i == typeof(IFoo));
}
Run Code Online (Sandbox Code Playgroud)

结果:

ImplementsIFooDirectly(typeof(IFoo)); // false
ImplementsIFooDirectly(typeof(Bar)); // false
ImplementsIFooDirectly(typeof(Foo)); // true
ImplementsIFooDirectly(typeof(IBar)); // true
Run Code Online (Sandbox Code Playgroud)

它不会查找从中派生的所有接口IFoo,它只是向上传递继承/接口实现链,并查看是否IFoo存在于除类型的确切级别之外的任何级别.

它还检测接口是否通过基类型继承.不确定这是不是你想要的.

尽管如此,正如其他人已经说过的那样,如果这对您来说真的是一个要求,那么您的设计可能会遇到问题.(编辑:刚刚注意到你的问题纯粹是假设的.那当然没关系:))