首页 > 解决方案 > 无法更改数组的元素值

问题描述

首先,我将在这里粘贴我的代码,以便我更容易解释发生了什么。

[Column("SolvedBoard")]
public string _SolvedBoard { get; set; }

[NotMapped]
public int[,] SolvedBoard {
    get {
        return JsonConvert.DeserializeObject<int[,]>(_SolvedBoard);
    }

    set {
        _SolvedBoard = JsonConvert.SerializeObject(value, Formatting.Indented);
    }
}

如您所见,我的 int[,] 数组有一个自定义的 setter 和 getter。这似乎是使用 Entity Framework 将我的数组存储到我的表中的最干净的选择。但是在我制作了 setter 和 getter 之后,我无法更改数组的元素。

举个例子

SolvedBoard[0,0] = 1;

SolvedBoard[0,0] 从构造函数的初始化开始仍然保持为 0。那是调用 setter get 并且 _SolvedBoard 获取数组的 JSON 版本(全为 0)的时候。

这是我在这里的第一篇文章,所以不确定这是否足够的信息。

编辑:

SolvedBoard.SetValue(1, 0, 0);

也不行。

标签: c#arraysindexing

解决方案


欢迎来到堆栈溢出。如果我的理解是正确的,Solved[0,0] = 1;就不要调用setter。该行等效于以下内容:

int[,] board = Solved; // calls the getter
board[0,0] = 1; // does not call the getter or the setter

我认为如果你做这样的事情会起作用:

int[,] board = Solved;
board[0,0] = 1;
Solved = board; // call the setter

推荐阅读