【问题标题】:Unable to change array's element value无法更改数组元素值
【发布时间】:2021-10-28 02:34:03
【问题描述】:

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

[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# arrays indexing


【解决方案1】:

欢迎来到 Stack Overflow。如果我的理解是正确的,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

【讨论】:

  • 是我自己想出来的。但由于我在类中有多个位置可以更改 SolvedBoard 中特定元素的值,我不知道这是否是最好的解决方案。
猜你喜欢
  • 2021-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-18
  • 2016-05-26
  • 2023-03-26
  • 1970-01-01
  • 2016-08-08
相关资源
最近更新 更多