将IEnumerable转换为ICollection时会发生什么

时间:2012-09-18 09:54:15

标签: c# casting ienumerable icollection

鉴于以下情况:

var collection = myEnumerable as ICollection<MyType>;

引擎盖下会发生什么? ICollection有一个count属性。这个演员是否枚举了可枚举的计数或更多涉及的事情?

2 个答案:

答案 0 :(得分:8)

什么都没发生。如果myEnumerable确实是ICollection<MyType> collection将包含它。否则它将是null。就这么简单。

答案 1 :(得分:1)

重点:

当您将IEnumerable类型对象转换为ICollection时,它将被引用键入。

例如,从集合中删除也会从IEnumerable集合中删除该项目。

例如:

IEnumerable<AnyClass> enumerableObject;

ICollection<AyClass> collectingObject = (ICollection<AnyClass>)enumerableObject;

foreach(var item in collectingObject){

collectingObject.Remove(item);

}

如果您访问enumerableObject的值,您会发现它已更新,并删除了所有值。