2010-11-12 29 views
2

如何將ObjectCollection項目添加到IList(SomeType)? 我試過:將ObjectCollection中的項目添加到IList(Of SomeType)

For Each obj As SomeType In listBox.Items 'ObjectCollection 
    MyObject.ItProperty.Add(obj) 'IList 
Next 

沒有成功。 謝謝。

+0

我想你錯過了一些文字。它以「我嘗試過:」結尾。 – 2010-11-12 11:50:47

+0

我改變了這一點。對不起,謝謝。 – thom 2010-11-12 11:54:03

回答

1

如果可能的話,非通用IList接口將是最簡單的方法:

IList list = (IList)MyObject.ItProperty; 
list.Add(obj); 

否則,你將有:

  • 找到合適的T(使用反射)
  • IList<T>解決Add方法(使用反射)
  • 調用Add法(使用反射)

的反射,尤其是泛型,是不是很好。

作爲替代 - 如果您有4.0,您可以嘗試使用dynamic,但請注意,這隻能看到公共API。值得一試,但(僅當IList失敗):

dynamic list = MyObject.ItProperty; 
list.Add(obj); // let's hope Add isn't an explicit interface implementation 
0

你能添加什麼失敗,其中的一些細節?你的代碼應該工作。

如果您在「For Each obj」行收到異常"Unable to cast object of type 'XXX' to type 'SomeType'.",那麼listBox.Items集合中至少有一個項目不是'SomeType'類型。