【发布时间】:2012-03-21 21:15:48
【问题描述】:
我有以下课程:
public class DrawableComplexEntity2D
{
public List<GameComponent> Components { get; set; }
// anothers properties, constructor, methods...
}
public class BoardCell : DrawableComplexEntity2D
{
public GoalPersonGroup GoalPersonGroup { get; set; }
public void CreateGoalPersonGroup(Goal groupType)
{
this.GoalPersonGroup = new GoalPersonGroup(groupType)
base.Components.Add(this.GoalPersonGroup);
}
}
所以,当我这样做时:
BoardCell cell1 = new BoardCell();
cell1.CreateGoalPersonGroup(Goal.Type1);
BoardCell cell2 = new BoardCell();
cell2.CreateGoalPersonGroup(Goal.Type2);
cell1.GoalPersonGroup = cell2.GoalPersonGroup;
当我用 cell2.GoalPersonGroup 更新 cell1.GoalPersonGroup 时,cell1.GoalPersonGroup 会更新,但是 cell1 的 base.Components 内部的 cell1.GoalPersonGroup 不会改变,仍然是 cell1 的值而不是 cell2。为什么?
【问题讨论】:
-
如果你还没有编写代码来改变它,为什么要改变它?
-
当我在 List
中添加一个对象时,我添加的不是对象的引用吗? -
你添加到
List<T>的是对对象的引用,而不是对属性的引用。您正在用对完全独立对象的引用替换该属性。Components列表仍然包含对原始对象的引用,因为这是您添加到其中的。
标签: c# list pass-by-reference