gpt4 book ai didi

c# - 在类型上查找直接实现的接口(interface)

转载 作者:太空狗 更新时间:2023-10-29 20:02:13 24 4
gpt4 key购买 nike

在以下情况下调用 typeof(Bar).GetInterfaces() 时,该方法返回 IFoo 和 IBar。


interface IFoo {}<br/>
interface IBar : IFoo {}<br/>
class Bar : IBar {}

有没有办法在Bar上只找到即时界面(IBar)?

最佳答案

不,编译代码中没有“立即”接口(interface)这样的东西。您的类(class)被有效地编译为:

class Bar : IBar, IFoo { }

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

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

关于c# - 在类型上查找直接实现的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2055411/

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