问题
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