c# 反射泛型列表计数

本文关键字:列表 泛型 反射 | 更新日期: 2023-09-27 18:35:13

没有比这更干净的方法来使用反射来获取列表计数?

 Boolean include = false;
 foreach (PropertyInfo item in props)
        {
            var pt = item.PropertyType;                
            String listType = pt.GetGenericArguments()[0].Name;
             // Is there a better solution than this?
             switch (listType)
                            {
                                case "jsonResult":
                                    var list = v as List<jsonResult>;
                                    include =  list.count > 0;
                                    break;                                
                            }
        }
    )

我已经从谷歌搜索中尝试了各种想法,但没有任何运气。

c# 反射泛型列表计数

我不完全理解"v"变量是什么,但如果它是一个对象,当它是一个集合时,你想获取它的计数,你可以这样做:

var count = GetCount(v);
if (!count.HasValue)
    continue; // Or any other code here
    
include =  count.Value > 0;

"GetCount"方法:

private static int? GetCount(object @object)
{
    var collection = @object as System.Collections.ICollection;
    if (collection == null)
        return null;
    
    return collection.Count;
}