2012-10-29 58 views
0

我想在其他地方協方差泛型集合

var d = myGrid.ItemSource as IEnumerable<Object>;  
var e = d as ICollection<dynamic>; 
e.Add(new anotherclass()); 

我需要在程序的不同地區訪問的ItemSource做到這一點

List<anotherclass> ls = new List<anotherclass> {new anotherclass{Name = "me"}};  
myGrid.ItemSource = ls; 

。我需要將項目添加到列表中,而無需編譯時間類型信息。投向IEnumerable的作品,但因爲我需要添加項目集合我需要比這更多,因此試圖將其轉換爲集合。

怎麼可能?

回答

3

List<T>實施IList。所以只要你確定你要添加的正確類型的對象,你可以用這個接口的Add方法:

var d = (IList)myGrid.ItemSource;   
d.Add(new anotherclass()); 
+0

+1,這很有效,謝謝。 – Jimmy

0

試試這個:

var d =(List<anotherclass>) myGrid.ItemSource; 
d.Add(new anotherclass()); 

我認爲這是更好地做直接演員。如果您使用,因爲它會在嘗試添加時拋出nullreferenceException。有更好的描述出錯的invalidCastException會更好。

+0

謝謝。但我不知道在添加 – Jimmy

+1

時的實際類型但是您知道您想添加另一個類的實例。 –

+0

不,重點是ItemSource在程序的某個部分設置,任何類都可以在其中。在應用程序的一部分,我想編寫一個通用例程來處理itemsource,而不管它包含在其中的對象的類型。 – Jimmy

2

問題不在於:「它爲什麼會起作用?」,因爲實際上它不起作用。它編譯但它會拋出一個NullReferenceException
d as ICollection<dynamic>將返回null,因爲List<anotherclass>不是ICollection<dynamic>,但ICollection<anotherclass>ICollection<T>不是協變。

該解決方案已由KooKiz提供。

+1

+1,謝謝你的解釋。 – Jimmy