C#将源列表中的元素添加到其他列表也会将其添加到源列表中

C# Add element from sourcelist to other list will add it also on sourcelist

所以我遇到了一些无法解决的奇怪错误:

我正在制作一种赛车游戏,有一个包含所有唯一检查点的 class RaceManager 和一个位于汽车上的 class RaceAgent,也包含 RaceManager 的检查点,称为未通过的 CP。每次汽车通过其目标检查点时,它都会将其从未通过的 CP 中删除。

但是,如果我想将第一个检查点添加到未通过的 CP,以便赛车必须 return 到 start/finish 才能完成一轮,每辆车也会将其添加到 RaceManager 的检查点.

RaceAgent.cs:

void Setup(){ //gets called at beginning and on new round; not when finished
    unpassedCPs = RaceManager.rm.checkpoints; //copy all cps
    if(laps > 0){ //true when roundcourse, else it will finish at last checkpoint
    //if i comment out next line, RaceManager will not add its first checkpoint, but here we are adding to RaceAgents' unpassedCPs
        unpassedCPs.Add(RaceManager.rm.checkpoints[0]); //for returning back to start/finish

    }

    SetTargetCP(RaceManager.rm.checkpoints[0]);
}
unpassedCPs = RaceManager.rm.checkpoints; //copy all cps

除非 checkpoints 是 属性 并且在其 get 中包含代码以创建 checkpoints 的副本,否则此行不会复制所有 cps。 相反,在语句 unpassedCPs 之后引用与 RaceManager.rm.checkpoints 相同的集合,因此当您 运行

unpassedCPs.Add(RaceManager.rm.checkpoints[0])

类似于运行ning RaceManager.rm.checkpoints.Add(RaceManager.rm.checkpoints[0])

要解决您的问题,您需要根据检查点创建一个新的 List,例如:

unpassedCPs = new List<Checkpoint>(RaceManager.rm.checkpoints);