How can members of IEnumerable<T> be modified?

最后都变了- 提交于 2019-12-12 04:22:15

问题


In an earlier question about generic variance, I was informed that members of IEnumerable<T> can be modified. How can that be done and, seeing as variance violations arise when a covariant type can be modified, how then can IEnumerable<T> be covariant on T?


回答1:


You have to distinguish modifying the sequence from modifying the elements of it.

You can modify elements without any problems, since you can't modify the type of the object by using properties and functions on it.

And thus, this is all fine, since all elements in IEnumerable<T> are either T or type derived from T.

Such violations you mention could only happen if you could could have, for example, an object of type Base inside IEnumerable<Derived>



来源:https://stackoverflow.com/questions/38506448/how-can-members-of-ienumerablet-be-modified

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!