gpt4 book ai didi

c# - 在 C# 中运行代码行后,变量的值会发生变化吗?

转载 作者:太空宇宙 更新时间:2023-11-03 20:16:27 25 4
gpt4 key购买 nike

我以前遇到过几次这个问题。这是一个示例代码:

public void moveRight(int x, int y, int rows, int columns)
{
char[,] imatrix = GameInstance.vexedGame.getLastMatrix(); // <-- creating a variable and initializing it.
char letter = imatrix[x, y]; // Doesn't matters
char[,] oldMatrix = imatrix; // Creating a new var that is the same as the variable created before
if (imatrix[x, (y + 1)] == '-')
{
//LINE 1
GameInstance.vexedGame.setLastMatrix(oldMatrix); //Setting the var of this class to the old matrix (until here everything's fine)
imatrix[x, (y + 1)] = letter;
imatrix[x, y] = '-'; //Changing the matix
//LINE 2
GameInstance.vexedGame.setActualMatrix(imatriz); //Setting the actual matrix.
}
}

发生的事情是,当我在整个过程中放置​​断点时,当我到达//LINE 1 时,该值与更改前的矩阵副本一起保存。在我对//LINE 2 进行更改后,不仅 imatrix 的值发生了变化,而且第一个矩阵的值也发生了变化,因此 GameInstance.vexedGame.setLastMatrix 发生了变化。我真的不知道为什么会这样,如果有人能帮助我,我将不胜感激。谢谢!

(抱歉我的英语不好)

最佳答案

那是因为它是一个数组,而数组是引用类型。

当你这样做的时候

char[,] oldMatrix = imatrix;

这会创建一个浅拷贝。即内存中的地址被传递给oldmatrix。现在它们是两个变量但指向内存中的相同地址。如果你先改变,第二个显然必须改变。

为了避免这种使用循环将每个值从第一个复制到第二个或

做一个深拷贝。

关于c# - 在 C# 中运行代码行后,变量的值会发生变化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16370441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com