如何动态确定类型是否是使用反射的接口?

How to determine dynamically if type is an Interface using reflection?

首先,这个问题不是这个我已经读了 100 遍的 post 的重复(请继续阅读问题):How to determine if a type implements an interface with C# reflection

我正在使用反射在运行时动态地遍历对象的属性以操作和添加数据。对我来说,根本问题自然是,你 不能 实例化一个 Interface 的实例,因此我的代码使用 Activator.CreateInstance 以后下游 一定不能 是 运行 反对 Interface 类型或 Interface 类型的集合。

假设我在 Person class 上有以下内容:

public IList<Address> addresses1 {get ; set; } \ This property **should** flag being an Interface public List<Address> addresses2 {get ; set; } \ This property **should NOT** flag being an Interface

在反思 属性 时使用以下代码,我 可以 找出 属性 是否实现了 Interface:

propertyTypeFromReflection.GetInterfaces().Any()

我遇到的问题是 IList<Address>List<Address> 都有上面的语句 return true。这是因为即使是我们所知的 List<T> 实际上也实现了一系列接口(即 IListICollectionIEnumerable 等)。

由于我是动态地进行这项调查,所以我不知道如何测试我的类型是否实现了 specific Interface,例如 all 示例显示,例如 link 我在开头 posted 执行以下操作:

typeof(IMyInterface).IsAssignableFrom(typeof(MyType)) typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))

我需要帮助来确定 属性 对象 属性 是否动态地和聚焦地 直接 是一个接口而不是具体类型?所有示例都需要将已知的 Interface 测试为已知的具体类型,但由于这是动态发生的,我不知道如何完成此操作?

您可以使用 Type.IsInterface 属性 https://msdn.microsoft.com/en-us/library/system.type.isinterface(v=vs.110).aspx