可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I was just curious about this: the following code will not compile, because we cannot modify a foreach iteration variable:
foreach (var item in MyObjectList)
{
item = Value;
}
But the following will compile and run:
foreach (var item in MyObjectList)
{
item.Value = Value;
}
Why is the first invalid, whereas the second can do the same underneath (I was searching for the correct english expression for this, but I don't remember it. Under the...? ^^ )
回答1:
foreach is a read only iterator that iterates dynamically classes that implement IEnumerable, each cycle in foreach will call the IEnumerable to get the next item, the item you have is a read only reference, you can not re-assign it, but simply calling item.Value
is accessing it and assigning some value to a read/write attribute yet still the reference of item a read only reference.
回答2:
The second isn't doing the same thing at all. It's not changing the value of the item
variable - it's changing a property of the object to which that value refers. These two would only be equivalent if item
is a mutable value type - in which case you should change that anyway, as mutable value types are evil. (They behave in all kinds of ways which the unwary developer may not expect.)
It's the same as this:
private readonly StringBuilder builder = new StringBuilder();
// Later...
builder = null; // Not allowed - you can't change the *variable*
// Allowed - changes the contents of the *object* to which the value
// of builder refers.
builder.Append("Foo");
See my article on references and values for more information.
回答3:
You can't modify a collection while it's being enumerated. The second example only updates a property of the object, which is entirely different.
Use a for
loop if you need to add/remove/modify elements in a collection:
for (int i = 0; i < MyObjectList.Count; i++)
{
MyObjectList[i] = new MyObject();
}
回答4:
If you look at the language specification you can see why this is not working:
The specs say that a foreach is expanded to the following code:
E e = ((C)(x)).GetEnumerator();
try {
V v;
while (e.MoveNext()) {
v = (V)(T)e.Current;
embedded-statement
}
}
finally {
… // Dispose e
}
As you can see the current element is used to call MoveNext() one. So if you change the current element the code is 'lost' and can't iterate over the collection.
So changing the element to something else doesn't make any sense if you see what code the compiler is actually producing.
回答5:
It would be possible to make item
mutable. We could change the way the code is produced so that:
foreach (var item in MyObjectList)
{
item = Value;
}
Became equivalent to:
using(var enumerator = MyObjectList.GetEnumerator())
{
while(enumerator.MoveNext())
{
var item = enumerator.Current;
item = Value;
}
}
And it would then compile. It would not however affect the collection.
And there's the rub. The code:
foreach (var item in MyObjectList)
{
item = Value;
}
Has two reasonable ways for a human to think about it. One is that item
is just a place-holder and changing it is no different to changing item
in:
for(int item = 0; item < 100; item++)
item *= 2; //perfectly valid
The other is that changing item would actually change the collection.
In the former case, we can just assign item to another variable, and then play with that, so there's no loss. In the latter case this is both prohibited (or at least, you can't expect to alter a collection while iterating through it, though it doesn't have to be enforced by all enumerators) and in many cases impossible to provide (depending on the nature of the enumerable).
Even if we considered the former case to be the "correct" implementation, the fact that it could be reasonably interpreted by humans in two different ways is a good enough reason to avoid allowing it, especially considering we can easily work around that in any case.
回答6:
Because the first one doesn't make much sense, basically. The variable item is controlled by the iterator (set on each iteration). You shouldn't need to change it- just use another variable:
foreach (var item in MyObjectList)
{
var someOtherItem = Value;
....
}
As for the second, there are valid use cases there- you might want to iterate over an enumeration of cars and call .Drive() on each one, or set car.gasTank = full;
回答7:
The point is that you cannot modify the collection itself while iterating over it. It is absolutely legal and common to modify the objects the iterator yields.
回答8:
Because the two are not the same. When doing the first, you might expect to change the value that is in the collection. But the way foreach
works, there is no way that could have been done. It can only retrieve items from the collection, not set them.
But once you have the item, it's an object like any other and you can modify it in any (allowed) way you can.
回答9:
Use for loop instead of foreach loop and assign value. it will work
foreach (var a in FixValue)
{
for (int i = 0; i < str.Count(); i++)
{
if (a.Value.Contains(str[i]))
str[i] = a.Key;
}
}