Tengo un montón de Colecciones IEnumerable cuyo número exacto y tipos están sujetos a cambios frecuentes (debido a la generación automática de código).Cómo invocar System.Linq.Enumerable.Count <> en IEnumerable <T> utilizando Reflection?
se ve algo como esto:
public class MyCollections {
public System.Collections.Generic.IEnumerable<SomeType> SomeTypeCollection;
public System.Collections.Generic.IEnumerable<OtherType> OtherTypeCollection;
...
En tiempo de ejecución que quiero para determinar cada tipo y es contar sin tener que volver a escribir el código después de cada generación de código. Así que estoy buscando un enfoque genérico utilizando la reflexión. El resultado que estoy buscando es algo así como:
MyType: 23
OtherType: 42
Mi problema es que no puedo entender cómo invocar correctamente el método Count. Aquí es lo que tengo hasta ahora:
// 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);
}
}
}
¿Es "MyCollections" un tipo de variable/campo/propiedad? Parece que lo estás usando como los dos. –
Su recuento MethodInfo-reference es nulo. Arregle eso y probablemente el código funcione. –
Lo sentimos, el ejemplo dado no es exacto. Lo he arreglado – mbi