我有一个问题要问你们。
我有一个如下所示的课程:
public class Node
{
public int Kova1; // Kova 1
public int Kova2; // Kova 2
public int Kova3; // Kova 3
public int ActionNo; // Yapılan İşlem
public Node(int kova1, int kova2, int kova3, int actionNumber)
{
Kova1 = kova1;
Kova2 = kova2;
Kova3 = kova3;
ActionNo = actionNumber;
}
public Node(int kova1, int kova2, int kova3)
{
Kova1 = kova1;
Kova2 = kova2;
Kova3 = kova3;
}
public Node()
{
}
public Node AnneNode;
}
以及这些功能:
public void CocukNodeOlustur(LinkedList<Node> Acik, LinkedList<Node> Kapali, Node temp)
{
Node cocukState;
Node temp2 = temp;
for (int i = 0; i < 12; i++)
{
cocukState = YeniStateOlustur(temp, i);
if ((ActionKontrol(cocukState)) && (GoalBulundu(Acik, Kapali, cocukState)) &&
((cocukState.Kova1 != temp2.Kova1) && (cocukState.Kova2 != temp2.Kova2) && (cocukState.Kova3 != temp2.Kova3)))
{
cocukState.AnneNode = temp;
Acik.AddFirst(temp);
}
}
}
public Node YeniStateOlustur(Node s, int j)
{
int tempKova1, tempKova2, tempKova3;
Node yeniCocuk = new Node();
yeniCocuk = s;
yeniCocuk.ActionNo = j;
// Gelen numaraya göre uygulanan işlemin seçimi yapılıyor.
switch (j)
{
case 0:
{
yeniCocuk.Kova1 += (3 - yeniCocuk.Kova1);
yeniCocuk.Kova2 += 0;
yeniCocuk.Kova3 += 0;
}
break;
case 1:
{
yeniCocuk.Kova1 += 0;
yeniCocuk.Kova2 += (5 - yeniCocuk.Kova2);
yeniCocuk.Kova3 += 0;
}
break;
}
return yeniCocuk;
}
在主要功能中
Node temp = new Node();
while (!(Acik.Count == 0))
{
p.CocukNodeOlustur(Acik, Kapali, temp);
Kapali.AddLast(temp);
}
所以当我调试我的程序时,我看到每当代码跳转到 YeniStateOlustur ()函数时,程序中的所有Node实例都会受到 YeniStateOlustur ()。 似乎函数中的实例会覆盖Node类的所有实例。
我不明白为什么会这样?
我怎样才能克服这个?
我最好的问候和长篇大论的故事。
答案 0 :(得分:1)
问题是所有节点都是同一个实例。您的示例代码仅包含“new Node()”两次,而在第二种情况下(在方法YeniStateOlustur
内),新实例立即被丢弃。因此,该函数返回传递给它的同一节点:
public Node YeniStateOlustur(Node s, int j)
{
int tempKova1, tempKova2, tempKova3;
Node yeniCocuk = new Node();
yeniCocuk = s;
//...
return yeniCocuk;
}
在方法CocukNodeOlustur
中,所有节点变量都指向同一个节点:
public void CocukNodeOlustur(LinkedList<Node> Acik, LinkedList<Node> Kapali, Node temp)
{
// here, temp == temp
Node cocukState;
// now, temp == temp and cocukState is uninitialized.
Node temp2 = temp;
// now, temp == temp, temp2 == temp, and cocukState is uninitialized.
for (int i = 0; i < 12; i++)
{
cocukState = YeniStateOlustur(temp, i);
// now, temp == temp, temp2 == temp, and cocukState == temp
if ((ActionKontrol(cocukState)) && (GoalBulundu(Acik, Kapali, cocukState)) &&
((cocukState.Kova1 != temp2.Kova1) && (cocukState.Kova2 != temp2.Kova2) && (cocukState.Kova3 != temp2.Kova3)))
{
cocukState.AnneNode = temp;
Acik.AddFirst(temp);
}
}
}
您的代码似乎假设Node是一个值类型(struct),但它显然是一个引用类型(类)。如果你不确定这些差异,你应该退后一步,做一些阅读和实验。
快速修复可能是将Node的声明更改为结构,但我建议不要这样做。使用结构进行编程可能非常棘手,如果您对结构和类之间的差异的理解不稳定,则尤其如此。