开发者

Get the Count of a List of unknown type

I am calling a function that returns an object and in certain circumstances this object will be a List.

A GetType on this object might gives me:

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

or

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

etc

I don't care what this type is, all I want is a Count.

I've tried:

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

but this gives me an AmbiguousMatchException which I can't seem to get around without knowing the type.

I've tried casting to IList but I get:

Unable to cast object of type 'System.Collections.Generic.List'1[ClassN]' to type 'System.Collections.Generic.IList'1[System.Object]'.

UPDATE

Marcs answer below is actually correct. The reason it wasn't working for me is that I have:

using System.Collections.Generic;

at th开发者_JAVA百科e top of my file. This means I was always using the Generic versions of IList and ICollection. If I specify System.Collections.IList then this works ok.


Cast it to ICollection and use that .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);
}


You could do this

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

assuming you want to do this via reflection that is.


Use GetProperty instead of GetMethod


You can do this

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


This could help...

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜