c# - C#中通过反射获取接口(interface)的基接口(interface)

标签 c# reflection

<分区>

如何通过反射获取接口(interface)的基接口(interface)?我试图调用 BaseType 属性,但它的值为空。之后我需要找到接口(interface)的通用类型类。

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

Type oType = typeof(ISomeInterfaceForItem);

Type oBase = oType.BaseType; // equals null

public interface ISomeInterfaceForItem: ISomeInterface<Foo>
{        
}

public interface ISomeInterface<T>
{
}

最佳答案

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

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

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

关于c# - C#中通过反射获取接口(interface)的基接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37674074/

相关文章:

c# - 有人可以向我解释一下这个 LINQ/Entity Framework 查询实际上是如何工作的吗?

c# - 如何使用其类型名称实例化泛型类?

.net - Type.GetMethods 的 BindingFlags 不包括属性访问器

go - 如何通过反射初始化结构指针

Scala Object - 从字符串获取引用(在 Scala 2.10 中)

c# - 删除远程文件?

c# - 构建 Service Fabric Web Api 时出现错误,无法从 Fabric.StatelessServiceContext 转换为 Fabric.ServiceInitializationParameters

java - 在java中提取唯一的调用者信息

c# - 设置 BinaryFormatter.TypeFormat 似乎无效

javascript - jquery datepicker 和 asp.net c# 空值