你好我在這一段代碼一個真的奇怪的行爲:C#多維數組值驟變
public class IGraphics
{
public int[,] screen;
private int[,] world;
private int[,] entitys;
private int[,] buffer;
private int screenW;
private int screenH;
public IGraphics(int screenW, int screenH) {
this.screenH = screenH;
this.screenW = screenW;
screen = new int[screenW + 1, screenH];
buffer = new int[screenW + 1, screenH];
}
public void loadWorld(int[,] world) {
this.world = world;
}
public void clear() {
screen = new int[screenW + 1, screenH];
world = new int[screenW, screenH];
for (int y = 0; y < world.GetLength(1); y++) {
for (int x = 0; x < world.GetLength(0); x++) {
world[x, y] = 0;
}
}
}
private void loadScreen() {
}
private void updateEntitys()
{
entitys = new int[screenW, screenH];
List<GameObject> EntRow = Common.world.getEntitys();
for (int i = 0; i < EntRow.Count(); i++)
{
entitys[EntRow[i].x, EntRow[i].y] = EntRow[i].Icon;
}
}
public void draw() {
updateEntitys();
for (int y = 0; y < screen.GetLength(1); y++)
{
for (int x = 0; x < screen.GetLength(0) - 1; x++)
{
if (entitys[x, y] == 0)
{
screen[x, y] = world[x, y];
}
else
{
screen[x, y] = entitys[x, y];
}
}
screen[screen.GetLength(0) - 1, y] = 123;
}
if (buffer.Cast<int>().SequenceEqual(screen.Cast<int>()))
{
return;
}
Console.Clear();
buffer = screen;
for (int y = 0; y < screen.GetLength(1); y++) {
for (int x = 0; x < screen.GetLength(0); x++) {
if (screen[x, y] == 123)
{
Console.WriteLine();
}
else {
Console.Write(objectStore.getIcon(screen[x, y]));
}
}
}
}
}
問題就來了在Draw()函數,其中i設置屏幕的值[,]數組出於某種原因,它也改變了緩衝區[,]數組的值,然後控制器也嘗試在單獨的類中移動緩衝區[,],但我遇到了同樣的問題。
有人作爲解釋?
呃......也許是因爲'buffer = screen;'?我認爲編譯器完成你要求的工作並不奇怪。 – Jon
我想你打算將屏幕「複製」到緩衝區,但是相反,您將緩衝區分配給屏幕的引用,所以這兩個變量現在指向相同的數組。嘗試使用克隆或複製或其他方式複製數組。我認爲它的屏幕。複製到 – Eric
同意以上。否則,向自己(和其他人)證明,通過編寫一個非常簡單的測試用例來演示,改變另一個會改變另一個。那麼我們可以更好地思考這個問題。 – Les