我調用一個返回對象的函數,在某些情況下,這個對象將是一個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,那麼這工作正常。
難道我還需要一個類型有關係嗎? –
2010-08-05 18:53:11
也許我做錯了,但是這給了我錯誤:使用泛型類型「了System.Collections.Generic.ICollection」要求「1」類型參數 –
2010-08-05 18:56:39
@克里斯,列表直接實現ICollection的(非通用),它有一個'.Count'屬性。不需要類型。爲清晰起見添加了示例代碼 –
Marc
2010-08-05 18:56:42