Possiedo un numero di raccolte IEnumerable il cui numero esatto e tipi è soggetto a frequenti modifiche (a causa della generazione automatica del codice).Come richiamare System.Linq.Enumerable.Count <> su IEnumerable <T> utilizzando Reflection?
Sembra qualcosa di simile a questo:
public class MyCollections {
public System.Collections.Generic.IEnumerable<SomeType> SomeTypeCollection;
public System.Collections.Generic.IEnumerable<OtherType> OtherTypeCollection;
...
In fase di esecuzione che voglio per determinare ogni tipo ed è contare senza dover riscrivere il codice dopo ogni generazione del codice. Quindi sto cercando un approccio generico usando la riflessione. Il risultato che sto cercando è qualcosa di simile:
MyType: 23
OtherType: 42
Il mio problema è che io non riesco a capire come richiamare il metodo Count correttamente. Ecco quello che ho finora:
// Handle to the Count method of System.Linq.Enumerable
MethodInfo countMethodInfo = typeof(System.Linq.Enumerable).GetMethod("Count", new Type[] { typeof(IEnumerable<>) });
PropertyInfo[] properties = typeof(MyCollections).GetProperties();
foreach (PropertyInfo property in properties)
{
Type propertyType = property.PropertyType;
if (propertyType.IsGenericType)
{
Type genericType = propertyType.GetGenericTypeDefinition();
if (genericType == typeof(IEnumerable<>))
{
// access the collection property
object collection = property.GetValue(someInstanceOfMyCollections, null);
// access the type of the generic collection
Type genericArgument = propertyType.GetGenericArguments()[0];
// make a generic method call for System.Linq.Enumerable.Count<> for the type of this collection
MethodInfo localCountMethodInfo = countMethodInfo.MakeGenericMethod(genericArgument);
// invoke Count method (this fails)
object count = localCountMethodInfo.Invoke(collection, null);
System.Diagnostics.Debug.WriteLine("{0}: {1}", genericArgument.Name, count);
}
}
}
"MyCollections" è un tipo di una variabile/campo/proprietà? Sembra che tu stia usando entrambi. –
Il tuo numero MethodInfo-reference è null. Risolto il problema e il codice probabilmente funzionerebbe. –
Siamo spiacenti, l'esempio indicato non è accurato. L'ho risolto – mbi