【问题标题】:Get the Count of a List of unknown type获取未知类型列表的计数
【发布时间】:2021-03-31 11:50:07
【问题描述】:

我正在调用一个返回对象的函数,在某些情况下,该对象将是一个列表。

此对象上的 GetType 可能会给我:

{System.Collections.Generic.List`1[Class1]}

{System.Collections.Generic.List`1[Class2]}

我不在乎这个类型是什么,我想要的只是一个伯爵。

我试过了:

Object[] methodArgs=null;
var method = typeof(Enumerable).GetMethod("Count");
int count = (int)method.Invoke(list, methodArgs);

但这给了我一个 AmbiguousMatchException,我似乎无法在不知道类型的情况下绕过它。

我尝试投射到 IList,但我得到:

无法将类型为“System.Collections.Generic.List'1[ClassN]”的对象转换为类型“System.Collections.Generic.IList'1[System.Object]”。

更新

Marcs 下面的答案实际上是正确的。它对我不起作用的原因是我有:

using System.Collections.Generic;

在我的文件顶部。这意味着我一直在使用 IList 和 ICollection 的通用版本。如果我指定 System.Collections.IList 则可以。

【问题讨论】:

    标签: c# generics reflection


    【解决方案1】:

    将其转换为 ICollection 并使用 .Count

    using System.Collections;
    
    List<int> list = new List<int>(Enumerable.Range(0, 100));
    
    ICollection collection = list as ICollection;
    if(collection != null)
    {
      Console.WriteLine(collection.Count);
    }
    

    【讨论】:

    • 难道我还需要一个类型 吗?
    • 也许我做错了什么,但这给了我:错误 1 ​​使用泛型类型 'System.Collections.Generic.ICollection' 需要 '1' 类型参数
    • @Chris, List 直接实现具有.Count 属性的ICollection(非泛型)。无需类型。为了清楚起见,添加了示例代码。
    • @Chris,我试着把它做成一个完全独立的例子,希望能有所帮助。
    • 如果我指定 System.Collections.ICollection 或 System.Collections.IList - 这现在确实有效。因为我使用过 System.Collections.Generic;它正在使用这些接口的通用版本。谢谢
    【解决方案2】:

    你可以这样做

    var property = typeof(ICollection).GetProperty("Count");
    int count = (int)property.GetValue(list, null);
    

    假设您想通过反射来做到这一点。

    【讨论】:

    • 我喜欢这个,但这仅在列表实际上 一个 ICollection 类型时才有效。我不认为 OP 的问题总是如此。
    • 诚然,这有点难说,但由于给出的例子都是List&lt;T&gt;,这适用于给定的情况。但是,从公认的答案来看,在这种情况下似乎真的没有理由使用反射。如果不需要反射,只需转换为适当的类型会容易得多。
    • 对我不起作用:“使用泛型类型 'ICollection' 需要 1 个类型参数”
    【解决方案3】:

    使用 GetProperty 代替 GetMethod

    【讨论】:

      【解决方案4】:

      你可以这样做

      var countMethod = typeof(Enumerable).GetMethods().Single(method => method.Name == "Count" && method.IsStatic && method.GetParameters().Length == 1);
      

      【讨论】:

        【解决方案5】:

        这可能会有所帮助...

                if (responseObject.GetType().IsGenericType)
                {
                    Console.WriteLine(((dynamic) responseObject).Count);
                }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-04-18
          • 2011-05-20
          • 1970-01-01
          • 2019-03-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-29
          相关资源
          最近更新 更多