2015-08-28 97 views
0

如何缩短此代码?如果我没有弄错像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); 
} 
+4

Write方法重复性任务.... – Eser

+0

或写类的结构来完成工作 - 基本上与“重复任务的写入方法”相同 – St0fF

回答

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; 
}