Tengo una matriz de PropertyInfo que representa las propiedades de una clase. Algunas de estas propiedades son de tipo ICollection<T>
, pero T varía a través de las propiedades - Tengo algunos ICollection<string>
, algunos ICollection<int>
, etc.¿Cómo puedo encontrar el tipo de T en una colección C# genérica de T cuando todo lo que sé es el tipo de la colección?
I pueden identificar fácilmente cuál de las propiedades son de tipo ICollection<>
utilizando el método GetGenericTypeDefinition() en tipo, pero me resulta imposible obtener el tipo de T - la int o cadena en mi ejemplo anterior.
¿Hay alguna manera de hacerlo?
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
}
}
Maldita sea! Me venciste por 20 segundos. Cruzamos :-) – Steven
@Steven: ¡Acabas de conseguir a Jon Skeeted! –
Estaba llamando a GetGenericArguments en genericDefinition, no en typeOfProperty. He corregido mi descuido y ahora todo está bien. El comentario que eliminé hizo que tu comentario no tenga sentido, disculpas. – Jason