如何缩短此代码?如果我没有弄错,像temp = temp2这样的东西在c#中不起作用,因为它们会创建浅层副本而不是深层副本。这不是整个代码ofc
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);
}
答案 0 :(得分:1)
您可以使用以下内容轻松缩小代码第一部分的大小:
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;
}