如何在C#中检查接口是否扩展了另一个接口?

the*_*onk 6 .net c# inheritance

Type.IsSubclassOf方法只适用于两个具体的类型,例如

public class A {}
public class B : A {}
typeof(B).IsSubclassOf(typeof(A)) // returns true
Run Code Online (Sandbox Code Playgroud)

有没有办法找出一个接口是否扩展另一个?例如

public interface IA {}
public interface IB : IA {}
Run Code Online (Sandbox Code Playgroud)

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

her*_*ter 12

你可以做

bool isAssignable = typeof(IA).IsAssignableFrom(typeof(IB));
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我猜你会得到你需要的信息,但当然也不仅适用于接口.

我假设你有Type对象,如果你有实际的实例,这更短,更清晰,更高效:

public interface ICar : IVehicle { /**/ }

ICar myCar = GetSomeCar();
bool isVehicle = myCar is IVehicle;
Run Code Online (Sandbox Code Playgroud)