如何在不更改原始字符串的情况下创建和更改新的字符串[] []?

时间:2019-05-29 08:11:27

标签: c#

我知道这是由引用而不是值传递引起的问题,但是我不确定该如何解决。

我有一个字段变量string[][] _cubeState,它代表2x2 Rubiks多维数据集的状态。这个锯齿状的数组表示任何旋转之前多维数据集的状态,并且应该在每次旋转之后更新,但只有在我的rotate方法返回并覆盖它之后才更新。

实际上发生的是,当我到达newCube[0][index] = _cubeState[0][index + 10];行时,此行同时更新了我的newCube数组和原始_cubeState数组。由于newCube引用了cubeState,因此它也在更新原始对象。如何解决此问题,以便仅在方法返回后更新cubeState?

private string[][] _cubeState;

public Rubiks () {
    _cubeState = new string[][] {
        new [] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" },
        new [] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }
    };

    _cubeState = RotateAcw (0);
}

public string[][] RotateAcw (int index) {
    string[][] newCube = { _cubeState[0], _cubeState[1] };

    newCube[0][index] = _cubeState[0][index + 10];
    newCube[1][index] = _cubeState[1][index + 10];

    return newCube;
}

3 个答案:

答案 0 :(得分:2)

您不能像这样复制锯齿状的数组:

val ids: List<AttachmentId> = serviceHub.attachments.queryAttachments(
  AttachmentQueryCriteria.AttachmentsQueryCriteria(
    filenameCondition = Builder.equal("some name")
  )
)
val attachments: List<Attachment?> = ids.map { id -> serviceHub.attachments.openAttachment(id) }

您实际上并没有复制内部数组。

要复制内部数组,可以使用http://central.maven.org/maven2/com/fasterxml/jackson/core/jackson-core/2.9.9/。一种方法是这样:

string[][] newCube = { _cubeState[0], _cubeState[1] };

答案 1 :(得分:2)

这是复制锯齿状数组的方法:

string[][] cubeState = new string[][] {
    new [] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" },
    new [] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }
};

string[][] newCube = cubeState.Select(x => x.ToArray()).ToArray();

答案 2 :(得分:1)

Array.Clone的替代方案更短,更慢:

string[][] newCube = Array.ConvertAll(_cubeState, x => x.Clone());