2010-08-05 18 views
5

我調用一個返回對象的函數,在某些情況下,這個對象將是一個List。獲取未知類型列表的計數

這個目標可能在的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的]」。

UPDATE

榨渣回答以下實際上是正確的。它不是爲我工作的原因是,我有:

using System.Collections.Generic; 

在我的文件的頂部。這意味着我總是使用IList和ICollection的通用版本。如果我指定System.Collections.IList,那麼這工作正常。

回答

7

將它轉換爲ICollection的和使用.Count

List<int> list = new List<int>(Enumerable.Range(0, 100)); 

ICollection collection = list as ICollection; 
if(collection != null) 
{ 
    Console.WriteLine(collection.Count); 
} 
+2

難道我還需要一個類型有關係嗎? – 2010-08-05 18:53:11

+0

也許我做錯了,但是這給了我錯誤:使用泛型類型「了System.Collections.Generic.ICollection 」要求「1」類型參數 – 2010-08-05 18:56:39

+0

@克里斯,列表直接實現ICollection的(非通用),它有一個'.Count'屬性。不需要類型。爲清晰起見添加了示例代碼 – Marc 2010-08-05 18:56:42

0

使用的getProperty而不是GetMethod

+0

這將返回一個null – 2010-08-05 18:56:58

3

你能做到這一點

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

假設你要通過反射是這樣做。

+0

我喜歡這個,但這隻有當列表實際上是一個ICollection類型時才起作用。我認爲OP的問題並不總是如此。 – Marc 2010-08-05 19:03:23

+0

無可否認,這有點難以分辨,但是既然給出的例子都是'List ',這對於給定的情況是適用的。然而,看看接受的答案,似乎在這種情況下真的沒有理由使用反射。如果不需要反射,只需投射到適當的類型就容易得多。 – 2010-08-05 19:08:32

+0

對我不起作用:「使用泛型類型'ICollection '需要1個類型參數」 – 2018-03-10 10:37:19

0

你可以做到這一點

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