C# 如何通过反射获取接口基类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/538541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 07:18:04  来源:igfitidea点击:

How to get interface basetype via reflection?

c#reflectioninterface

提问by Kevin Driedger

public interface IBar {} 
public interface IFoo : IBar {}

typeof(IFoo).BaseType == null

How can I get IBar?

我怎样才能获得 IBar?

采纳答案by BFree

Type[] types = typeof(IFoo).GetInterfaces();

Edit: If you specifically want IBar, you can do:

编辑:如果你特别想要 IBar,你可以这样做:

Type type = typeof(IFoo).GetInterface("IBar");

回答by Coincoin

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.

如果您只想知道一种类型是否与另一种类型隐式兼容(我怀疑这就是您正在寻找的),请使用 type.IsAssignableFrom(fromType)。这等效于 'is' 关键字,但具有运行时类型。

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))) {
    // ...
}

回答by Paul-Jan

In addition to what the other posters wrote, you can get the first interface from the GetInterface() list (if the list is not empty) to get the direct parent of IFoo. This would be the exact equivalent of your .BaseType attempt.

除了其他发帖人所写的,您还可以从 GetInterface() 列表(如果列表不为空)中获取第一个接口,以获取 IFoo 的直接父级。这将完全等同于您的 .BaseType 尝试。