通过引用的foreach是否

通过引用的foreach是否

本文介绍了通过引用的foreach是否()迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一下:

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



时'物镜'一个清单内的相应对象的参考,以便当更改属性的变化将在一旦构造某处对象实例坚持?

Is 'obj' a reference to the corresponding object within the list so that when I change the property the change will persist in the object instance once constructed somewhere?

推荐答案

OBJ 是集合中的当前对象的引用(假设 MyClass的实际上是一个类)。如果你通过引用改变任何属性,你改变的对象,就像你所期望的。

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.

注意但是,你不能改变的变量 OBJ 本身,因为它是迭代变量。如果你尝试,你会得到一个编译错误。这意味着,你不能空它,如果你迭代值类型,你不能修改任何成员,将被改变的值。

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.

在C#语言规范状态(8.8.4)

The C# language specification states (8.8.4)

迭代变量相当于
A只读局部变量以
范围延伸过嵌入式
语句。

这篇关于通过引用的foreach是否()迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 03:26