【问题标题】:Get base interface of an interface by reflection in C# [duplicate]通过C#中的反射获取接口的基本接口[重复]
【发布时间】:2016-10-07 01:03:05
【问题描述】:

如何通过反射获得接口的基本接口?我试图调用 BaseType 属性,但它的值为 null。之后我需要找到接口的泛型类。

我需要从这个示例中的ISomeInterfaceForItem 类型中找到Foo 类型。

Type oType = typeof(ISomeInterfaceForItem);

Type oBase = oType.BaseType; // equals null

public interface ISomeInterfaceForItem: ISomeInterface<Foo>
{        
}

public interface ISomeInterface<T>
{
}

【问题讨论】:

  • 感谢@Jon Skeet 指出我的错误。我已经更正了问题。
  • 接口似乎具有 BaseType 是由 C# 语法造成的错觉。不是那样的,你只是继承了实现其他接口的需要。请改用 oType.GetInterfaces()。

标签: c# reflection


【解决方案1】:

接口不参与继承,所以BaseType 没有意义。相反,您需要查看给定类型实现了哪些类型的接口:

oType
  .FindInterfaces((t, _) => t.IsGenericType && t.GetGenericTypeDefinition() 
                            == typeof(ISomeInterface<>), null)
  .Select(i => i.GetGenericArguments().First())

请注意,一个类可以实现ISomeInterface&lt;&gt; 的多个变体——例如class MyClass : ISomeInterface&lt;Foo&gt;, ISomeInterface&lt;Bar&gt; - 这就是为什么上面示例的结果是一个可枚举的类型,而不仅仅是一个类型。

【讨论】:

    【解决方案2】:

    您可以使用GetInterface() 获取继承的接口,并使用GetGenericArguments() 枚举泛型参数:

    Type generic = typeof(I2).GetInterface("ISomeInterfaceForItem`1")?.
                              GetGenericArguments().FirstOrDefault();
    

    【讨论】:

      猜你喜欢
      • 2010-10-07
      • 1970-01-01
      • 1970-01-01
      • 2010-09-09
      • 1970-01-01
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多