gpt4 book ai didi

c# - 只查找非继承接口(interface)?

转载 作者:可可西里 更新时间:2023-11-01 08:41:36 25 4
gpt4 key购买 nike

我试图通过反射对类的接口(interface)执行查询,但是方法 Type.GetInterfaces() 也返回所有继承的接口(interface)。

等等

public class Test : ITest { }

public interface ITest : ITesting { }

代码

typeof(Test).GetInterfaces();

将返回一个包含ITestITestingType[],因为我只想要ITest,是否有另一种方法允许您指定继承?

谢谢,亚历克斯。

编辑:从下面的答案中我收集到了这一点,

Type t;
t.GetInterfaces().Where(i => !t.GetInterfaces().Any(i2 => i2.GetInterfaces().Contains(i)));

以上似乎有效,如果无效请在评论中纠正我

最佳答案

你可以尝试这样的事情:

Type[] allInterfaces = typeof(Test).GetInterfaces();
var exceptInheritedInterfaces = allInterfaces.Except(
allInterfaces.SelectMany(t => t.GetInterfaces())
);

所以,如果你有这样的事情:

public interface A : B
{
}

public interface B : C
{
}

public interface C
{
}

public interface D
{
}

public class Test : A, D
{
}

代码将返回AD

关于c# - 只查找非继承接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7563269/

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