【问题标题】:c# Reflection Generic List Countc# 反射泛型列表计数
【发布时间】:2021-04-16 06:17:25
【问题描述】:

有没有更简洁的方法来使用反射获取列表计数?

 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# generics reflection


    【解决方案1】:

    我没有完全理解什么是“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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多