【问题标题】:How to use reflection to get the number of items in a list如何使用反射来获取列表中的项目数
【发布时间】:2016-06-21 19:32:14
【问题描述】:

我有一个有几个List<T> 属性的类。我需要能够动态确定给定列表的大小。

下面是我到目前为止的代码。我怎样才能摆脱 switch 语句并将其作为一个一般性语句?我很想投给List<T>,但这不起作用。

switch (Inf.GetType()
            .GetProperty(propertyName)
            .GetValue(Inf)
            .GetType()
            .UnderlyingSystemType.GenericTypeArguments[0]
            .Name)
        {
            case "String":
                dynamicListCount = ((List<string>)Inf.GetType().GetProperty(propertyName).GetValue(Inf)).Count;
                break;
            case "Int32":
                dynamicListCount = ((List<Int32>)Inf.GetType().GetProperty(propertyName).GetValue(Inf)).Count;
                break;
            default:
                throw new Exception("Unknown list type");
        }

【问题讨论】:

  • 你为什么不投成IList
  • 不知道你为什么不使用List&lt;T&gt;.Count

标签: c# list generics reflection


【解决方案1】:

您应该将其类型转换为IList,因为类型化的泛型List&lt;&gt; 实现了接口IList。就像评论所暗示的一样。 (交叉邮件)

List<string> items = new List<string>();

items.Add("item1");
items.Add("item2");


int count = ((IList)items).Count;

MessageBox.Show(count.ToString());

【讨论】:

    【解决方案2】:

    List&lt;T&gt; 实现了IList,它具有Count 属性(继承自ICollection)。

    您可以简单地将值转换为 IList 并获得如下计数:

    IList list = (IList) Inf.GetType()
            .GetProperty(propertyName)
            .GetValue(Inf);
    
    var count = list.Count;
    

    【讨论】:

    • 我可以发誓我尝试投射到 IList。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-23
    相关资源
    最近更新 更多