Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 获取未知类型列表的计数_C#_Generics_Reflection - Fatal编程技术网

C# 获取未知类型列表的计数

C# 获取未知类型列表的计数,c#,generics,reflection,C#,Generics,Reflection,我正在调用一个返回对象的函数,在某些情况下,该对象将是一个列表 此对象上的GetType可能会提供: {System.Collections.Generic.List`1[Class1]} 或 等 我不管这是什么类型的,我只想要一个计数 我试过: Object[] methodArgs=null; var method = typeof(Enumerable).GetMethod("Count"); int count = (int)method.Invoke(list, methodArgs

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

此对象上的GetType可能会提供:

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

我不管这是什么类型的,我只想要一个计数

我试过:

Object[] methodArgs=null;
var method = typeof(Enumerable).GetMethod("Count");
int count = (int)method.Invoke(list, methodArgs);
但这给了我一个模棱两可的例外,在不知道类型的情况下,我似乎无法绕过它

我试着去投IList,但我得到:

无法将“System.Collections.Generic.List”1[ClassN]”类型的对象强制转换为“System.Collections.Generic.IList”1[System.object]”类型

更新

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

using System.Collections.Generic;

在我档案的顶端。这意味着我总是使用IList和ICollection的通用版本。如果我指定System.Collections.IList,则此操作正常。

将其强制转换为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);
}
使用系统集合;
列表=新列表(可枚举的范围(0,100));
ICollection collection=作为ICollection列出;
if(集合!=null)
{
Console.WriteLine(collection.Count);
}

使用GetProperty而不是GetMethod

您可以这样做

var property = typeof(ICollection).GetProperty("Count");
int count = (int)property.GetValue(list, null);
假设你想通过反射来实现这一点

你可以这样做

var countMethod = typeof(Enumerable).GetMethods().Single(method => method.Name == "Count" && method.IsStatic && method.GetParameters().Length == 1);
这可能有助于

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

我还需要一个类型吗?也许我做错了什么,但这给了我:错误1使用泛型类型'System.Collections.generic.ICollection'需要'1'类型arguments@Chris,列表直接实现ICollection(非泛型),它具有
.Count
属性。不需要类型。为清晰起见,添加了示例代码。@Chris,我试图使其成为一个完全独立的示例,希望这会有所帮助。如果我指定System.Collections.ICollection或System.Collections.IList,这实际上现在可以工作了。因为我使用System.Collections.Generic;它使用这些接口的通用版本。谢谢,我喜欢这样,但这只在列表实际上是ICollection类型时才起作用。我不认为OP的问题总是这样。诚然,这有点难说,但由于给出的示例都是
List
,因此这适用于给定的情况。然而,从公认的答案来看,在这种情况下似乎真的没有理由使用反射。如果不需要反射,则直接强制转换到适当的类型会容易得多。对我来说不起作用:“使用泛型类型'ICollection'需要1个类型参数”
        if (responseObject.GetType().IsGenericType)
        {
            Console.WriteLine(((dynamic) responseObject).Count);
        }