[英]How do I determine the generic type of an implemented interface using reflection?
[英]How to determine dynamically if type is an Interface using reflection?
对于初学者,此问题不是我已阅读100次(请继续提问)的重复: 如何确定类型是否使用C#反射实现接口
我正在使用反射在运行时动态地遍历对象的属性以操纵和添加数据。 对我来说,根本问题是自然,你不能实例的实例Interface
,因此使用我的代码Activator.CreateInstance
后下游不得对发现的各类跑出Interface
或集合Interface
类型。
假设我在Person
类中具有以下内容:
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>
的问题是IList<Address>
和List<Address>
都有上面的语句返回true
。 这是因为,即使我们知道的List<T>
实际上也实现了许多接口(即IList
, ICollection
, IEnumerable
等)。
由于我是动态进行调查的,所以我不知道如何测试我的类型是否实现了特定的 Interface
如所有示例所示,例如我一开始发布的链接,它执行以下操作:
typeof(IMyInterface).IsAssignableFrom(typeof(MyType))
typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))
我需要帮助确定对象属性Property是否动态且重点突出,是否直接是Interface而不是具体类型? 所有示例都需要测试已知Interface
到已知具体类型的代码,但是由于这是动态发生的,所以我不知道该如何完成?
您可以使用Type.IsInterface
属性https://msdn.microsoft.com/zh-cn/library/system.type.isinterface(v=vs.110).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.