简体   繁体   English

在foreach循环中修改对象的值

[英]Modifying value of object within foreach loop

I defined a list of rectangles called enemies, and I'm trying to move through the rectangles in the list and decrement their X value, but I am getting an error "cannot modify 'i' because it is a foreach iteration variable." 我定义了一个叫做敌人的矩形列表,我试图通过列表中的矩形移动并递减它们的X值,但是我得到一个错误“无法修改'我',因为它是一个foreach迭代变量。” I'm wondering what is wrong with this and if there is a correct way of going about it. 我想知道这有什么问题,如果有正确的方法去做。

        foreach (Rectangle i in enemies)
        {

            i.X --:

        }

Value types are copied by value ; 值类型按值复制; that's why they're called "value types". 这就是为什么他们被称为“价值类型”。 When you do this, you are making a copy of the rectangle and then mutating the copy . 当你这样做,你可以将这个矩形的副本 ,然后变异副本 Now, it just so happens that the foreach loop makes an immutable copy of the value and tells you that you cannot change it, which is good, because it just caught your bug. 现在,恰好是foreach循环生成值的不可变副本并告诉您不能更改它,这很好,因为它只是捕获了您的错误。 Had you been making that change to a mutable copy you might not have found the bug for a long time. 如果您将更改变为可变副本,则可能很长时间没有找到该错误。

Your Enemy type should probably be a reference type, not a value type. 您的Enemy类型应该是引用类型,而不是值类型。 Have the enemy contain a rectangle, not be a rectangle. 有敌人包含一个矩形, 不是一个矩形。 You can then mutate the rectangle in the reference to the enemy. 然后你可以在对敌人的引用中改变矩形。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM