Does foreach() iterate by reference?

前端 未结 10 1263
佛祖请我去吃肉
佛祖请我去吃肉 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-05 00:11

    You can in this instance (using a List) but if you were to be iterating over the generic IEnumerable then it becomes dependant on its implementation.

    If it was still a List or T[] for instance, all would work as expected. The big gotcha comes when you are working with an IEnumerable that was constructed using yield. In this case, you can no longer modify properties of T within an iteration and expect them to be present if you iterate the same IEnumerable again.

提交回复
热议问题