How to get interface basetype via reflection?

前端 未结 3 1789
孤街浪徒
孤街浪徒 2020-12-05 14:01
public interface IBar {} 
public interface IFoo : IBar {}

typeof(IFoo).BaseType == null

How can I get IBar?

3条回答
  •  遥遥无期
    2020-12-05 14:24

    An interface is not a base type. Interfaces are not part of the inheritance tree.

    To get access to interfaces list you can use:

    typeof(IFoo).GetInterfaces()
    

    or if you know the interface name:

    typeof(IFoo).GetInterface("IBar")
    

    If you are only interested in knowing if a type is implicitly compatible with another type (which I suspect is what you are looking for), use type.IsAssignableFrom(fromType). This is equivalent of 'is' keyword but with runtime types.

    Example:

    if(foo is IBar) {
        // ...
    }
    

    Is equivalent to:

    if(typeof(IBar).IsAssignableFrom(foo.GetType())) {
        // ...
    }
    

    But in your case, you are probably more interested in:

    if(typeof(IBar).IsAssignableFrom(typeof(IFoo))) {
        // ...
    }
    

提交回复
热议问题