简体   繁体   English

如何使用反射确定已实现接口的通用类型?

[英]How do I determine the generic type of an implemented interface using reflection?

I am writing something that needs to discover the types of all the properties in an object at runtime, using reflection. 我写的东西需要使用反射在运行时发现对象中所有属性的类型。 I'm fine with simple properties, I just get the PropertyInfo and the type is directly available. 我对简单的属性没问题,我只获取了PropertyInfo并且该类型可以直接使用。 I can't work out what to do for generic collections, though. 但是,我不知道该如何处理通用集合。 For example, suppose I am handed an instance of the following class at runtime: 例如,假设我在运行时获得了以下类的实例:

public class AnyClass
  {
  public ICollection<int> ListOfInts;
  }

So I use Type.GetProperties and pretty soon I have my PropertyInfo object for ListOfInts . 因此,我使用Type.GetProperties并且很快我有了ListOfInts PropertyInfo对象。

What's my next step? 我下一步是什么? How do I go from having the PropertyInfo, to working out that it is a list of ints? 我如何从拥有PropertyInfo到确定它是一个整数列表? How can I determine the generic type ( <int> in this example case) of the collection from just the PropertyInfo ? 如何仅从PropertyInfo确定集合的通用类型(在本例中为<int> )?

您可以获取通用参数类型的名称:

propertyInfo.PropertyType.GetGenericArguments()[0].Name

I believe you are looking for generic arguments of the type. 我相信您正在寻找该类型的通用参数。 See PropertyInfo.PropertyType and Type.GenericTypeArguments 请参见PropertyInfo.PropertyTypeType.GenericTypeArguments

PropertyInfo.PropertyType.GenericTypeArgument

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何动态确定类型是否是使用反射的接口? - How to determine dynamically if type is an Interface using reflection? 如何限制仅由通用类型实现的接口 - How can I restrict an Interface to be implemented by only a generic type 如何通过反射设置作为通用接口的字段的值? - How do I set value of field that is a generic interface through reflection? 如何通过只有一个类型而不使用反射来访问一个类型实现的 static 抽象接口成员? - How to access a type's implemented static abstract interface members by having only a type without using reflection? 如何使用反射来查找开放泛型类型上的哪个开放泛型参数实现泛型接口? - How can I use reflection to find which open generic argument on an open generic type implements a generic interface? 如何使用反射在泛型类型中动态确定属性属于基类还是子类? - How to determine if the property belongs to Base class or sub class dynamically in generic type using reflection? 泛型参数-使用具体类型进行编译,但是实现的接口不会编译 - Generic parameter - using a concrete type compiles, but an implemented interface does not 如何确定类型是否使用 C# 反射实现接口 - How to determine if a type implements an interface with C# reflection 在C#中使用反射时,如何将接口指定为通用类型参数? - How to specify an interface as a generic type argument when using reflection in C#? C#:如何确定接口变量的类型? - C#: how do I determine type of an interface variable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM