Does foreach() iterate by reference?

前端 未结 10 1242
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-04 23:37

Consider this:

List obj_list = get_the_list();
foreach( MyClass obj in obj_list )
{
    obj.property = 42;
}

Is obj

相关标签:
10条回答
  • 2020-12-04 23:51

    Yes, that's also why you cannot alter the enumerable object in the context of the foreach statement.

    0 讨论(0)
  • 2020-12-04 23:52

    Well, without understanding exactly what you mean by "Iterate by reference", I can't answer specifically yes or no, but I can say that what's going on under the surface is that the .net framework is constructing an "enumerator" class for each time client code calls a foreach, for the life of the foreach, that maintains a reference pointer into the collection being iterated over, and each time your foreach iterates, ir "delivers" one item and "increments" the pointer or reference in the enumerator to the next item...

    This happens regardless of whether the items in the collection you are iterating over are values types or reference types.

    0 讨论(0)
  • 2020-12-04 23:54

    Yes, obj is a reference to the current object in the collection (assuming MyClass is in fact a class). If you change any properties via the reference, you're changing the object, just like you would expect.

    Be aware however, that you cannot change the variable obj itself as it is the iteration variable. You'll get a compile error if you try. That means that you can't null it and if you're iterating value types, you can't modify any members as that would be changing the value.

    The C# language specification states (8.8.4)

    "The iteration variable corresponds to a read-only local variable with a scope that extends over the embedded statement."

    0 讨论(0)
  • 2020-12-04 23:59

    obj is a reference to an item inside the List, hence if you change it's value it will persist. Now what you should be concerned about is whether or not get_the_list(); is making a deep copy of the List or returning the same instance.

    0 讨论(0)
  • 2020-12-05 00:00

    Yes, until you change the generic type from List to IEnumerable..

    0 讨论(0)
  • 2020-12-05 00:00

    Well, it happened to me that my changes were not updated in a foreach loop when I iterated through var collection:

    var players = this.GetAllPlayers();
    foreach (Player player in players)
    {
        player.Position = 1;
    }
    

    When I changed var to List it started working.

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