foreach() 是否按引用迭代? [英] Does foreach() iterate by reference?

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

问题描述

考虑一下:

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

obj 是否是对列表中相应对象的引用,以便当我更改属性时,一旦在某处构造,更改将保留在对象实例中?

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 本身,因为它是迭代变量.如果你尝试,你会得到一个编译错误.这意味着您不能将其设为 null,并且如果您正在迭代值类型,则不能修改任何成员,因为这会更改该值.

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)

"迭代变量对应一个只读的局部变量范围扩展到嵌入式声明."

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆