2011-05-10 62 views
2

可能重複:
How to iterate the List in Reflection
Problem with IEnumerable in Reflection問題與IEnumerable的反思性

嗨,

我在迭代反射列表面臨的一個問題。

var item = property.GetValue(obj,null); // We dont know the type of obj as it is in Reflection. 

foreach(var value in (item as IEnumerable)) 
{ 
    //Do stuff 
    } 

如果我這樣做,我會得到這樣的

錯誤使用泛型類型「System.Collections.Generic.IEnumerable」需要1個類型參數

請幫助我。

+0

你需要投到'IEnumerable '不IEnumerable – Stecya 2011-05-10 13:15:51

回答

9

類型IEnumerable與通用類型IEnumerable<T>之間有區別。目前它認爲你的意思是通用的,因爲你已經包含命名空間System.Collections.Generic;該錯誤消息正在抱怨,因爲您沒有正確書寫IEnumerable<T>泛型類型。

非泛型IEnumerable類型在System.Collections命名空間中聲明,因此添加對其的引用。 (using System.Collections;)。

如果你的意思是使用泛型類型,那麼你應該有這樣的:foreach(var value in (item as IEnumerable<string>))其中字符串是對象的類型item枚舉結束。

IEnumerableIEnumerable<T>以及本information about generic types.

+0

張貼我自己的答案,但你的更完整。 +1 – 2011-05-10 13:22:36

0

正如你已經問過這個問題的意見陳述。這個例子雖然有一個稍微不同的問題。您正在收到編譯器錯誤,因爲您的源文件中包含System.Collections.Generic命名空間(使用頂級子句)。該名稱空間包含IEnumerable的通用版本 - >IEnumerable<T>。你的演員因此而失敗。如果你想使用IEnumerable add 「using System.Collections」。