[英]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.PropertyType和Type.GenericTypeArguments
PropertyInfo.PropertyType.GenericTypeArgument
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.