Tôi có một bộ sưu tập IEnumerable mà số lượng chính xác và các loại có thể thay đổi thường xuyên (do tạo mã tự động).Làm thế nào để gọi System.Linq.Enumerable.Count <> trên IEnumerable <T> bằng cách sử dụng Reflection?
Nó trông giống như sau:
public class MyCollections {
public System.Collections.Generic.IEnumerable<SomeType> SomeTypeCollection;
public System.Collections.Generic.IEnumerable<OtherType> OtherTypeCollection;
...
Khi chạy tôi muốn xác định từng loại và nó đếm mà không cần phải viết lại mã sau mỗi thế hệ mã. Vì vậy, tôi đang tìm kiếm một cách tiếp cận chung bằng cách sử dụng sự phản chiếu. Kết quả tôi đang tìm kiếm là một cái gì đó như:
MyType: 23
OtherType: 42
Vấn đề của tôi là tôi không thể tìm cách gọi phương thức Đếm đúng cách. Dưới đây là những gì tôi có cho đến nay:
// 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);
}
}
}
Có phải "MyCollections" là một loại biến/trường/thuộc tính không? Bạn dường như đang sử dụng nó như cả hai. –
Số của bạn MethodInfo-tham chiếu là null. Sửa lỗi đó và mã có thể hoạt động. –
Xin lỗi, ví dụ đã cho không chính xác. Tôi đã sưa nó. – mbi