【问题标题】:Updating an object in child class, doesn't update the object inside List<T> in the base class更新子类中的对象,不会更新基类中 List<T> 中的对象
【发布时间】: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&lt;T&gt;对象的引用,而不是对属性的引用。您正在用对完全独立对象的引用替换该属性。 Components 列表仍然包含对原始对象的引用,因为这是您添加到其中的。

标签: c# list pass-by-reference


【解决方案1】:

列表,与所有其他变量一样,包含。对于引用类型(我假设 GoalPersonGroup 是),value 是一个 reference。如果我有以下情况:

object a = ...;
object b = ...;

a = b;

我所做的只是获取b(这是一个参考)的并将该值复制到a。在引用类型的情况下,我可以在该值上执行操作(例如调用a.SomeProperty = "foo";),并且这些相同的状态更改将反映在程序中该特定引用存储在多变的。换句话说,如果我要检查b.SomeProperty 的值,它会是"foo"

但是,更改变量中的值不会影响指向该值的其他变量(ref 参数的情况除外)。

您添加了一个指向您的List 引用的值。您还为属性分配了相同的值。这两个不同的内存位置包含相同的值,因此指向相同的实际对象。但是稍后您只是重新分配了属性的值,这意味着它现在具有与列表中存储的值不同的值。

【讨论】:

    【解决方案2】:

    是的,您对引用感到困惑。分配引用变量会分配被引用的东西。

    例如

    string str1 = new String("Hello");   //str1 has a reference to "Hello"
    string basestr = str1;               //basestr has a reference to "Hello" (NOT str1)
    
    string str2 = new String("Goodbye"); //str2 has a reference to "Goodbye"
    str1 = str2;                         //str1 has a reference to "Goodbye" (basestr still = hello)
    

    【讨论】:

      【解决方案3】:

      您只是更改了属性cell1.GoalPersonGroup 中的引用,而不是您添加到base.Components 的引用。要解决此问题,您必须在 GoalPersonGroup 的设置器中添加代码才能执行您想要的操作。

      【讨论】:

      • 当我在 List 中添加一个对象时,我添加的不是对象的引用吗?
      • @ViniciusOttoni:你添加了一个值,在引用类型的情况下是一个reference。但是稍后更改该值不会影响引用或任何其他碰巧具有相同值的变量。
      猜你喜欢
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多