【发布时间】:2013-08-23 10:14:04
【问题描述】:
我正在从 Java 转到 C#,并且正在编写一些示例程序。现在我遇到了一个不同对象的列表(IUnit),当我调用列表中的某个值来更改它的值时,它会更改所有值。我添加了对列表的引用 - 根据其他堆栈溢出问题。
所以我有以下课程
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 个。我将如何阻止它这样做?我添加了对列表的引用,所以我认为它会将其从原始列表中删除。我需要克隆列表吗?这行得通吗?
还是更多的设计问题?
谢谢!
【问题讨论】:
-
您是否在列表中多次添加了相同的
marine实例? -
你一开始就误解了
ref。您的ShotRandomGuy方法根本不需要使用ref。请参阅yoda.arachsys.com/csharp/parameters.html 您还应该了解自动实现的属性。 -
阅读以下内容,会有帮助:stackoverflow.com/questions/5501374/…
-
谢谢大家的帮助。