我有一个PropertyInfo数组,表示类中的属性.其中一些属性属于类型ICollection<T>,但T在属性中各不相同 - 我有一些ICollection<string>,有些ICollection<int>等等.
我可以ICollection<>通过在类型上使用GetGenericTypeDefinition()方法轻松识别哪些属性属于类型,但我发现无法获取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
}
}
Run Code Online (Sandbox Code Playgroud)
如果你知道它会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...
}
}
Run Code Online (Sandbox Code Playgroud)
当类型是某种类型实现 ICollection<T>但它本身可能是通用的时,它会变得更难.听起来你处于更好的位置:)