2012-10-29 94 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