Ho una matrice di PropertyInfo che rappresenta le proprietà in una classe. Alcune di queste proprietà sono di tipo ICollection<T>
, ma T varia tra le proprietà - ho qualche ICollection<string>
, alcuni ICollection<int>
, eccCome posso trovare il tipo di T in una collezione generica di C# di T quando tutto quello che so è il tipo di collezione?
posso facilmente identificare quale delle proprietà sono di tipo ICollection<>
utilizzando il metodo GetGenericTypeDefinition() su tipo, ma trovo impossibile ottenere il tipo di T - int o stringa nel mio esempio sopra.
C'è un modo per farlo?
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
}
}
Dannazione! Mi hai battuto per 20 secondi. Attraversiamo postato :-) – Steven
@Steven: hai appena ottenuto Jon Skeeted! –
Stavo chiamando GetGenericArguments su genericDefinition, non su typeOfProperty. Ho corretto la mia supervisione e ora tutto va bene. Il commento che ho cancellato ha reso il tuo commento privo di senso, scuse. – Jason