How is the iteration variable readonly?

前端 未结 2 603
北海茫月
北海茫月 2021-01-21 06:24

In 8.8.4 of the C# specification, it provides this example:

A foreach statement of the form

foreach (V v in x) embedded-stat         


        
相关标签:
2条回答
  • 2021-01-21 07:04

    The iteration variable is read-only because it is an error to write to it. Give it a try, and you'll see.

    It doesn't make a readonly field, and the documentation does not say that it makes a readonly field. It cannot possibly be a readonly field because it is not a field.

    Now, here is a subtle question. Suppose v is of mutable value type, and you call a method on the type which mutates a field of this, passing v. Make a prediction about what happens. Now try it; were you right? Can you explain what happened? What do you think now about the claim that v is "read-only"? Would you say that this is a bug, or the right behavior?

    Now try the same thing with a readonly field, and see what the results are. Do you think this is the right behaviour?

    0 讨论(0)
  • 2021-01-21 07:16

    There is special-case code in the compiler which enforces the read-only constraint on the iteration variable in a foreach block. It does not correspond to any modifier which is exposed in the language, so you can't explicitly declare local variables as read-only outside of this particular syntax.

    Conceptually, this constraint is applied before the expansion. That is, if there are any assignments to the iteration variable, the compiler generates an error. Otherwise the code is expanded. In the expanded code there is no particular constraints on v since it is just a regular local variable. Therefore the constraint does not exist in the IL either.

    So why is there this special-case read-only constraint with the foreach-syntax? Only the language designers can answer that, but I would guess it is just to avoid confusion. If the iterator variable was assignable, you might think you were able to modify the actual collection that way, but nothing would actually happen, since the underlying enumerator is read-only.

    0 讨论(0)
提交回复
热议问题