public void ConvertMoves(){ for (int i = 0; i maxDirections; i++) { Debug.Log("gimme tsMoves "+tSpossibleMoves[i].Count + " from " + this); possibleAttacks[i] = tSpossibleAttacks[i]; possibleAttacksInactive[i] = tSpossibleAttacksInactive[i]
public void ConvertMoves() { for (int i = 0; i < maxDirections; i++) { Debug.Log("gimme tsMoves "+tSpossibleMoves[i].Count + " from " + this); possibleAttacks[i] = tSpossibleAttacks[i]; possibleAttacksInactive[i] = tSpossibleAttacksInactive[i]; possibleAttackIndicators[i] = tSpossibleAttackIndicators[i]; possibleMoves[i] = tSpossibleMoves[i]; Debug.Log("Gimme moves(1) " + possibleMoves[i].Count + " from " + this); } for (int i = 0; i < maxDirections; i++) { tSpossibleAttacks[i].Clear(); tSpossibleAttacksInactive[i].Clear(); tSpossibleAttackIndicators[i].Clear(); tSpossibleMoves[i].Clear(); Debug.Log("Gimme moves(2) " + possibleMoves[i].Count + " from " + this); } }
所以调试日志报告以下内容:
gimme tsMoves 2 from JeanArc(Clone) (JeanArc)
Gimme moves(1) 2 from JeanArc(Clone) (JeanArc)
一切都很好,但后来……
Gimme moves(2) 0 from JeanArc(Clone) (JeanArc)
为什么要清除整个不同List变量的移动?
这不会创建列表项的副本:possibleAttacks[i] = tSpossibleAttacks[i]
它只是将对同一对象的引用复制到第二个变量中,因此可能攻击[i]和tSpossibleAttacks [i]现在都指向内存中的相同项.可以想象有两张信用卡可以访问一个银行账户.
您可以阅读有关参考类型here in Microsoft’s docs的更多信息.
正如Heinzi在下面的评论中指出的那样,你可以通过调用以下方式复制你的项目(因为它是一个列表):
possibleAttacks[i] = tSpossibleAttacks[i].ToList();
顺便说一下,如果你只想分配tSpossibleAttacks [i]然后重置它,你也可以这样做:
possibleAttacks[i] = tSpossibleAttacks[i]; tSpossibleAttacks[i] = new List<your_type_name_here>(); // this will overwrite the reference held by `tSpossibleAttacks[i]`.
请注意,如果列表包含引用类型,则列表中存在类似问题,例如:
public class Test { public string Name { get; set; } } List<Test> list1 = new List<Test>(); list1.Add(new Test() { Name = "John" }); List<Test> list2 = list1.ToList(); Console.WriteLine(list1[0].Name); // John Console.WriteLine(list2[0].Name); // John list2[0].Name = "Fred"; Console.WriteLine(list1[0].Name); // Fred Console.WriteLine(list2[0].Name); // Fred
因此,我建议您阅读值类型与引用类型以及引用如何在C#中工作.