How is the iteration variable readonly?

前端 未结 2 604
北海茫月
北海茫月 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?

提交回复
热议问题