gpt4 book ai didi

c# - 在列表上引用不改变值

转载 作者:太空狗 更新时间:2023-10-30 01:20:39 25 4
gpt4 key购买 nike

我正在从 Java 转向 C#,并编写了一些示例程序。现在我遇到了一个不同对象列表 (IUnit),当我调用列表中的某个值来更改它的值时,它会更改所有值。我添加了对列表的引用 - 根据其他堆栈溢出问题。

所以我有以下类(class)

interface IUnit
{
int HealthPoints { set; get; }
String ArmyType { get; }
}

这是我用来创建陆军类型(海军陆战队/步兵)列表的基类。实现是相同的,期望对类内部的值进行更改。

public class Infantry : IUnit
{
private int health = 100;
protected String armyType = "Infantry";
public int HealthPoints
{
get
{
return health;
}
set
{
health = value;
}
}
public String ArmyType
{
get
{
return armyType;
}
}

然后我用下面的代码初始化列表

 List<IUnit> army = new List<IUnit>(); 
Infantry infantry = new Infantry();
Marine marine = new Marine();
army.Add(Marine);

然后我有一个方法,直接减掉25点生命值。

    public void ShotRandomGuy(ref List<IUnit> army)
{
army[0].HealthPoints = army[0].HealthPoints - 25;
}

然后我调用该方法,如下所示。

 battle.ShotRandomGuy(ref army);

但是它从该列表中的所有对象中取出 25。我将如何阻止它这样做?我已经添加了对列表的引用,所以我认为它会把它从原始列表中删除。我需要克隆列表吗?那行得通吗?

还是更多的是设计问题?

谢谢!

最佳答案

看起来您多次将相同的单元实例添加到列表中。因此所有列表项都指向内存中的单个对象。修改任何项目都会修改该对象。

List<IUnit> army = new List<IUnit>(); 
Infantry infantry = new Infantry();

for(int i = 0; i < 10; i++)
{
// adds same instance each time
army.Add(infantry);
}

您应该在将单元添加到列表时实例化新单元。例如

List<IUnit> army = new List<IUnit>(); 

for(int i = 0; i < 10; i++)
{
// create new instance each time
Infantry infantry = new Infantry();
army.Add(infantry);
}

顺便说一句,你在这里不需要ref:

public void ShotRandomGuy(List<IUnit> army)
{
Random r = new Random();
var unit = army[r.Next(army.Count)];
unit.HealthPoints -= 25;
}

关于c# - 在列表上引用不改变值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18400261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com