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

Tar*_*riq 1 c# windows arrays 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);
        }
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ell 9

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

SomeType[] screenBottom = new SomeType[n];
for(int i = 0 ; i < screenBottom.Length ; i++)
    screenBottom[i] = theSameInstance;
Run Code Online (Sandbox Code Playgroud)

你可以简单地检查一下ReferenceEquals(screenBottom[0], screenBottom[1])- 如果它返回true,这就是问题所在.

注意,可能是所有数组项都不同,但它们都与同一个sourceRect实例通信; 你可以检查一下ReferenceEquals(screenBottom[0].sourceRect, screenBottom[1].sourceRect)

  • @DeeMac好吧,从理论上讲,数组可以包含不同的对象,每个对象都作为pass-thrus*传递给某个单独的底层对象,但这只是表达相同基本问题的一种更复杂的方式 (2认同)