对数组的操作

本文关键字:操作 数组 | 更新日期: 2023-09-27 18:10:18

如何缩短此代码?如果我没有弄错的话,像temp=temp2这样的东西在c#中不起作用,因为它们创建的是浅拷贝而不是深拷贝。这不是c

的全部代码
public struct node {
    public int[, ] state;
    public int ordering;
    public int parent;
 }
 if (temp.state[0, 1] == 0) {
    node temp1, temp2, temp3;
    temp1.state = new int[3, 3];
    temp2.state = new int[3, 3];
    temp3.state = new int[3, 3];
    temp1.parent = temp.ordering;
    temp2.parent = temp.ordering;
    temp3.parent = temp.ordering;
    temp1.ordering = temp.ordering + 1;
    temp2.ordering = temp.ordering + 2;
    temp3.ordering = temp.ordering + 3;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            temp1.state[i, j] = temp.state[i, j];
            temp2.state[i, j] = temp.state[i, j];
            temp3.state[i, j] = temp.state[i, j];
        }
    }
    temp1.state[0, 1] = temp1.state[0, 0];
    temp1.state[0, 0] = 0;
    temp2.state[0, 1] = temp2.state[0, 2];
    temp2.state[0, 2] = 0;
    temp3.state[0, 1] = temp3.state[1, 1];
    temp3.state[1, 1] = 0;
    new_nodes.Add(temp1);
    new_nodes.Add(temp2);
    new_nodes.Add(temp3);
 }

对数组的操作

你可以很容易地减少代码的第一部分的大小,像这样:

node temp1, temp2, temp3;
temp1 = CreateNode(temp, 1);
temp2 = CreateNode(temp, 2);
temp3 = CreateNode(temp, 3);
public node CreateNode(node oldNode, int increment)
{
    node newNode;
    /*Note the Clone() here instead of nested for loops.
      Works because it is a matrix of value type, so we are 
      not working with references inside the matrix.
      The two arrays now have different references.*/
    newNode.state = (int[,])oldNode.state.Clone(); 
    newNode.parent = oldNode.ordering;
    newNode.ordering = oldNode.ordering + increment;
}