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

标签 c# variables matrix

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

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/

相关文章:

c# - Selenium - 出现模态对话框 - 如何接受信息?

c# - Cannot modify the logical children for this node at this time because a tree walk is in progress 是什么意思?

C# Windows 窗体用户控件控件设计器支持

java - 有没有办法使用 C++ 从 Java 进程中读取值?

variables - lua中的全局和局部递归函数

matlab - 查找矩阵内向量元素的列位置

c++ - 如何将矩阵参数发送到 C++ 中的 main 函数

c# - ASP 2.0 和部分类

C# Selenium : passing a variable into XPath

在单个目标映射到多个源的情况下定位最接近源的目标并解决冲突的算法