gpt4 book ai didi

c# - 确定一个类是否实现了一个非常具体的接口(interface)

转载 作者:可可西里 更新时间:2023-11-01 08:42:06 28 4
gpt4 key购买 nike

关于这个主题有很多问题,但我有一个稍微修改过的版本。

我们有以下代码:

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

bool Implements_IFoo(Type type) { /* ??? */ }

现在,故事的转折点是:Implements_IFoo 方法应该只在 Type 仅实现 IFoo 而不是从 IFoo 派生的任何接口(interface)时返回 true。为了说明这里是这种方法的一些例子:

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

Implements_IFoo(typeof(Bar)); // Should return false as Bar type
// implements an interface derived from IFoo

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

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

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

最佳答案

我试了一下,因为它听起来很有趣,这对你的例子很有效:

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

结果:

ImplementsIFooDirectly(typeof(IFoo)); // false
ImplementsIFooDirectly(typeof(Bar)); // false
ImplementsIFooDirectly(typeof(Foo)); // true
ImplementsIFooDirectly(typeof(IBar)); // true

它不会查找从 IFoo 派生的所有接口(interface),它只是沿着继承/接口(interface)实现链向上移动,并查看 IFoo 是否存在于除类型的确切级别。

它还会检测接口(interface)是否通过基类型继承。不确定这是否是您想要的。

不过,正如其他人已经说过的那样,如果这确实是您的要求,那么您的设计可能有问题。 (编辑:刚刚注意到你的问题纯粹是假设性的。那当然没问题:))

关于c# - 确定一个类是否实现了一个非常具体的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10351535/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com