c# - 如何检查一个接口(interface)是否在 C# 中扩展了另一个接口(interface)?

标签 c# .net inheritance

Type.IsSubclassOf方法仅适用于两种具体类型,例如

public class A {}
public class B : A {}
typeof(B).IsSubclassOf(typeof(A)) // returns true

有没有办法查明一个接口(interface)是否扩展了另一个接口(interface)?例如

public interface IA {}
public interface IB : IA {}

我唯一能想到的是在 IB 上使用 GetInterfaces 并检查它是否包含 IA,有人知道另一种/更好的方法吗?

最佳答案

你可以做到

bool isAssignable = typeof(IA).IsAssignableFrom(typeof(IB));

我想这会为您提供在这种情况下所需的信息,而且当然不仅适用于接口(interface)。

我假设你有 Type 对象,如果你有实际的实例,这会更短、更清晰且性能更高:

public interface ICar : IVehicle { /**/ }

ICar myCar = GetSomeCar();
bool isVehicle = myCar is IVehicle;

关于c# - 如何检查一个接口(interface)是否在 C# 中扩展了另一个接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3892814/

相关文章:

c# - 如何在 C# 中将数据从指针复制到指针?

java - 继承、组合和默认方法

java - Hibernate 级联继承

c# - 如何将 @Scripts.Render 与 .Net Core 2.0 MVC 应用程序一起使用?

C# Linq SortedList过滤成SortedList

c# - 您在使用 Excel Interop 时遇到的最烦人/最奇怪的事情是什么

c++ - 通过 Derived::f2() 调用 f1() 时调用了谁的函数?

C# 互操作服务 - 使用 C dll - void*

来自通用抽象类的 C# 线程静态字段

.net - 如何通过 ILGenerator.Emit* 调用 'normal' 方法?