for循环中的每次迭代都会覆盖整个数组的值

时间:2014-03-20 12:19:28

标签: c# arrays windows for-loop windows-phone-8

我有一个for循环,遍历一个对象数组来设置对象绘制的值。以下是代码

for (int i = 0; i < screenBottom.Length; i++)
        {
            int newPostion = i * screenBottom[i].sourceRect.Width; 
            //go through sourceRect as we're using drawSimple mode
            screenBottom[i].sourceRect.X = newPostion; 
            screenBottom[i].Draw(spriteBatch);
        }

但是,每次设置sourceRect.X的新值时,都会覆盖数组中所有对象的sourceRect.X值。在for循环结束时,所有sourceRect.X的值等于只有最后一个值的值。通过一些测试,我发现这只发生在循环中。如果我更改循环外的值,则不会发生这种情况。请帮忙!

1 个答案:

答案 0 :(得分:9)

我怀疑数组包含相同的对象很多次,即意外:

SomeType[] screenBottom = new SomeType[n];
for(int i = 0 ; i < screenBottom.Length ; i++)
    screenBottom[i] = theSameInstance;

您可以使用ReferenceEquals(screenBottom[0], screenBottom[1])进行检查 - 如果它返回true,则问题就在于此。

请注意,所有数组项都可以 ,但它们都与同一个sourceRect实例通信;您可以使用ReferenceEquals(screenBottom[0].sourceRect, screenBottom[1].sourceRect)

进行检查
相关问题