[英]How to determine dynamically if type is an Interface using reflection?
For starters, this question is not a repeat of this post that I have read 100 times (please read on for question): How to determine if a type implements an interface with C# reflection 对于初学者,此问题不是我已阅读100次(请继续提问)的重复: 如何确定类型是否使用C#反射实现接口
I'm using reflection to iterate through properties on objects dynamically at runtime to manipulate and add data. 我正在使用反射在运行时动态地遍历对象的属性以操纵和添加数据。 The root issue for me is naturally, you cannot instantiate an instance of an
Interface
and therefore my code using Activator.CreateInstance
later downstream must not be ran against types found to be an Interface
or a collection of an Interface
type. 对我来说,根本问题是自然,你不能实例的实例
Interface
,因此使用我的代码Activator.CreateInstance
后下游不得对发现的各类跑出Interface
或集合Interface
类型。
Say I have the following on an Person
class: 假设我在
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
Using the following code while reflecting on the property I can find out if the property implements an Interface
: 在思考属性时使用以下代码,我可以确定该属性是否实现了
Interface
:
propertyTypeFromReflection.GetInterfaces().Any()
The problem I have is both IList<Address>
and List<Address>
have the statement above return true
. 我
IList<Address>
的问题是IList<Address>
和List<Address>
都有上面的语句返回true
。 That's because even List<T>
as we know actually implements a slew of Interfaces (ie IList
, ICollection
, IEnumerable
, etc.). 这是因为,即使我们知道的
List<T>
实际上也实现了许多接口(即IList
, ICollection
, IEnumerable
等)。
Since I am doing this investigation dynamically, I have no idea of how to test if my type implements a specific Interface
like all the examples show such as the link I posted at the beginning which do the following: 由于我是动态进行调查的,所以我不知道如何测试我的类型是否实现了特定的
Interface
如所有示例所示,例如我一开始发布的链接,它执行以下操作:
typeof(IMyInterface).IsAssignableFrom(typeof(MyType))
typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))
typeof(IMyInterface).IsAssignableFrom(typeof(MyType))
typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))
I need help determining if the object Property reflected upon dynamically and in focus, is directly an Interface as opposed to a concrete type? 我需要帮助确定对象属性Property是否动态且重点突出,是否直接是Interface而不是具体类型? All the examples require testing the known
Interface
to a known concrete type, but since this is happening dynamically I don't know how to accomplish this? 所有示例都需要测试已知
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.