
它看起来像这样:
public class MyCollections { public System.Collections.Generic.IEnumerable<SomeType> SomeTypeCollection; public System.Collections.Generic.IEnumerable<OtherType> OtherTypeCollection; ... 在运行时,我想确定每个Type和它的计数,而不必在每次代码生成后重写代码.所以我正在寻找使用反射的通用方法.我正在寻找的结果是这样的:
MyType: 23OtherType: 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); } } }解决方法 如果你坚持不懈努力; p 变化:
>如何获取泛型方法的countMethodInfo
> Invoke的参数
代码(注意obj是我的MyCollections实例):
MethodInfo countMethodInfo = typeof (System.linq.Enumerable).getmethods().Single( method => method.name == "Count" && method.Isstatic && method.GetParameters().Length == 1); 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(obj,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(null,new object[] {collection}); System.Diagnostics.DeBUG.Writeline("{0}: {1}",count); } } } 总结 以上是内存溢出为你收集整理的c# – 如何使用Reflection在IEnumerable上调用System.Linq.Enumerable.Count <>?全部内容,希望文章能够帮你解决c# – 如何使用Reflection在IEnumerable上调用System.Linq.Enumerable.Count <>?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)