【发布时间】:2011-04-02 13:01:08
【问题描述】:
我有一堆 IEnumerable 集合,它们的确切数量和类型经常更改(由于自动代码生成)。
看起来像这样:
public class MyCollections {
public System.Collections.Generic.IEnumerable<SomeType> SomeTypeCollection;
public System.Collections.Generic.IEnumerable<OtherType> OtherTypeCollection;
...
在运行时,我想确定每种类型并对其进行计数,而不必在每次代码生成后重写代码。所以我正在寻找一种使用反射的通用方法。我正在寻找的结果是这样的:
MyType: 23
OtherType: 42
我的问题是我不知道如何正确调用 Count 方法。这是我目前所拥有的:
// 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”是一种变量/字段/属性吗?你似乎同时使用它。
-
您的计数 MethodInfo-reference 为空。修复它,代码可能会工作。
-
对不起,给定的例子不准确。我已经修好了。
-
我不会为 .NET 中的通用通配符提供什么。 . .
-
在我阅读答案之前,谁能给我解释一下这个问题?
标签: c# generics reflection collections ienumerable