我尝试在两个不同的数组中存储相同的数据:一个是"spots“的二维数组,另一个是对象的数组,它也包含一个"spots”数组。
数组的索引是不同的,但我可以更改一个数组中的信息,它也会在另一个数组中更改。我的印象是数组包含引用类型,所以因为第二个数组(tileData)是由第一个数组(gameBoardData)组成的,所以当我更改tile中的数组时,为什么不更改gameBoardData中的数据?磁贴不是由对gameBoardData的引用构成的吗?如果不是,我该如何做我所描述的?
public Spot[,] gameBoardData { get; private set; }
public Tile[] tileData { get; private set; }
private void initializeBoard()
{
this.gameBoardData = new Spot[4, 4];
for (int row = 0; row < 4; row++)
{
for (int column = 0; column < 4; column++)
{
this.gameBoardData[row, column] = new Spot();
this.gameBoardData[row, column].pieceState = 0;
}
}
Tile tile1 = new Tile( new Spot[4] { gameBoardData[0, 0], gameBoardData[0, 1], gameBoardData[1, 1], gameBoardData[1, 0] });
Tile tile2 = new Tile(new Spot[4] { gameBoardData[0, 2], gameBoardData[0, 3], gameBoardData[1, 3], gameBoardData[2, 2] });
Tile tile3 = new Tile(new Spot[4] { gameBoardData[2, 0], gameBoardData[2, 1], gameBoardData[3, 1], gameBoardData[3, 0] });
Tile tile4 = new Tile(new Spot[4] { gameBoardData[2, 2], gameBoardData[2, 3], gameBoardData[3, 3], gameBoardData[3, 2] });
this.tileData = new Tile[4] { tile1, tile2, tile3, tile4 };
}发布于 2014-06-23 14:57:27
我不确定为什么这些更改没有反映给您。下面是一个示例控制台应用程序,其中反映了这些更改。
using System;
namespace test
{
class Program
{
static void Main(string[] args)
{
var board = new Board();
board.InitializeBoard();
}
}
public class Board
{
public Spot[,] gameBoardData { get; private set; }
public Tile[] tileData { get; private set; }
public void InitializeBoard()
{
this.gameBoardData = new Spot[4, 4];
for (int row = 0; row < 4; row++)
{
for (int column = 0; column < 4; column++)
{
this.gameBoardData[row, column] = new Spot();
this.gameBoardData[row, column].PieceState = 0;
}
}
Tile tile1 = new Tile(new Spot[4] { gameBoardData[0, 0], gameBoardData[0, 1], gameBoardData[1, 1], gameBoardData[1, 0] });
Tile tile2 = new Tile(new Spot[4] { gameBoardData[0, 2], gameBoardData[0, 3], gameBoardData[1, 3], gameBoardData[2, 2] });
Tile tile3 = new Tile(new Spot[4] { gameBoardData[2, 0], gameBoardData[2, 1], gameBoardData[3, 1], gameBoardData[3, 0] });
Tile tile4 = new Tile(new Spot[4] { gameBoardData[2, 2], gameBoardData[2, 3], gameBoardData[3, 3], gameBoardData[3, 2] });
this.tileData = new Tile[4] { tile1, tile2, tile3, tile4 };
tileData[0].Spots[0].PieceState = 25;
if (gameBoardData[0, 0].PieceState == 25)
{
Console.WriteLine("Changes Reflected");
Console.Read();
}
}
}
public class Spot
{
public int PieceState { get; set; }
}
public class Tile
{
public Spot[] Spots;
public Tile(Spot[] spots)
{
Spots = spots;
}
}
}发布于 2014-06-23 14:58:45
注意“new”关键字,您在
new Tile( new Spot[4] { gameBoardData[0, 0], gameBoardData[0, 1], gameBoardData[1, 1], gameBoardData[1, 0] });这样,您就可以使用gameBoardData的数据创建一个新的Tile对象。因为它是一个新对象,所以它不包含对原始对象的引用。
您想要做的是:
var gameBoardData_1 = new Spot[4, 4];
var tile1 = new Tile(gameBoardData_1);在内部,你只需将它添加到你正在使用的任何容器中,例如:
m_BoardList.Add(gameBoardData_1);https://stackoverflow.com/questions/24359743
复制相似问题