Why is foreach loop Read-Only in C#

后端 未结 3 1299
北海茫月
北海茫月 2020-11-29 11:22

Why is foreach loop a read only? I mean you can fetch the data but can\'t increase++ or decrease--. Any reason behind it? Yes I am a beginner :)

Exmaple:

         


        
3条回答
  •  悲&欢浪女
    2020-11-29 11:47

    Because the current element is returned by value(i.e. copied). And modifying the copy is useless. If it is a reference type you can modify the content of that object, but can't replace the reference.

    Perhaps you should read the documentation of IEnumerable and IEnumerator. That should make it clearer. The most important bit is that IEnumerable has a property Current of type T. And this property has only a getter, but no setter.

    But what would happen if it had a setter?

    • It would work well with arrays and Lists
    • It wouldn't work well with complex containers like hashtables, ordered list because the change causes larger changes in the container(for example a reordering), and thus invalidates the iterator. (Most collections invalidate the iterators if they get modified to avoid inconsistent state in the iterators.)
    • In LINQ it does make no sense at all. For example with select(x=>f(x)) the values are results of a function and have no permanent storage associated.
    • With iterators written with the yield return syntax it doesn't make sense either

提交回复
热议问题