我有一个PropertyInfo数组,表示一个类中的属性。其中一些属性的类型为ICollection<T>
,但是T随属性的不同而变化-我有一些ICollection<string>
,一些ICollection<int>
等。
通过在类型上使用GetGenericTypeDefinition()方法,我可以轻松地识别出哪些属性的类型为ICollection<>
,但是在上面的示例中,我发现无法获得T的类型-int或字符串。
有没有办法做到这一点?
IDocument item
PropertyInfo[] documentProperties = item.GetType().GetProperties();
PropertyInfo property = documentProperties.First();
Type typeOfProperty = property.PropertyType;
if (typeOfProperty.IsGenericType)
{
Type typeOfProperty = property.PropertyType.GetGenericTypeDefinition();
if (typeOfProperty == typeof(ICollection<>)
{
// find out the type of T of the ICollection<T>
// and act accordingly
}
}
最佳答案
如果您知道它将是ICollection<X>
但不知道X,那么使用 GetGenericArguments
相当简单:
if (typeOfProperty.IsGenericype)
{
Type genericDefinition = typeOfProperty.GetGenericTypeDefinition();
if (genericDefinition == typeof(ICollection<>)
{
// Note that we're calling GetGenericArguments on typeOfProperty,
// not genericDefinition.
Type typeArgument = typeOfProperty.GetGenericArguments()[0];
// typeArgument is now the type you want...
}
}
当类型是实现
ICollection<T>
但本身可能是通用类型的类型时,它会变得更加困难。听起来您处在更好的位置:)