[英]C# The items inside the list are changed when a new item is added
public List<Player> playerList = new List<Player>();
public List<Player> Player_A = new List<Player>();
for (int i = 0; i < playerList.Count; i++)
{
if (playerList[i].Id == 1)
{
playerList[i].hp = inputfiled.text;
Player_A(playerList[i]);
break;
}
}
将 playerlist [i] 添加到列表 player_A 后。 player_A 列表中的所有项目都已更改为相同,例如刚刚添加了 playerlist [i]。 例如:
playerlist[0].hp = 100
add playerlist[0] -> playerList_A.
playerList_A[0].hp = 100
playerlist[1].hp = 50.
add playerlist[0] -> playerList_A.
playerList_A[0].hp = 50 and playerList_A[1].hp = 50;
因此,当添加新项目时,将评估以前的项目。
将 playlist[0] 添加到 player_A 时,您在堆中添加引用该内存的地址 最好创建新的项目实例,然后添加到 player_a
列表中的项目正在更改是合乎逻辑的。 这是因为您有以下代码行:
playerList[i].hp = inputfiled.text;
您指的是 playerList 中的对象。 您似乎想创建一个新对象并将其添加到新列表中:Player_A
将您的代码更改为:
Player copiedPlayer = new Player();
copiedPlayer.Id = playerList[i].Id;
etc.
copiedPlayer.hp = 100;
Player_A.Add(copiedPlayer);
您还可以让播放器实现 IClonable 并克隆对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.