改变一个对象的属性,全部改变,为什么?

时间:2018-08-16 21:24:35

标签: class properties equals

当我发现某些图块在通用地图中而不是在局部地图中被更改(后来会合并到通用地图中)被更改时,我正在为一个简单的地图创建者进行编码...因此,我开始测试一些东西,对于某些东西发生这种情况的原因。如果我更改Type属性,为什么它返回相同的内容?

对第一个或第二个Tile的任何属性所做的任何更改均适用于两者。

        Tile first = new Tile(new CoordInt(0, 0), tileType.Wall);//create first tile new Tile(new CoordInt(int,int), (Enum)tileType)
        Tile second = first;//NEW Tile second equals first
        second.SetType(tileType.Floor);//property Type of the Tile named second is set to Floor (property set to { get; private set; })
        Debug.Log(first.ToLongString());
        Debug.Log(second.ToLongString());
        Debug.Log(first == second);

        //Console
        //Tile at (0, 0) from room -1 is a Floor and is Neutral
        //You CANNOT walk in it
        //Tile at (0, 0) from room -1 is a Floor and is Neutral
        //You CANNOT walk in it
        //True

        //Why does this return the same, if i'm changing the property only of the Tile named second and not of both?

1 个答案:

答案 0 :(得分:1)

您需要复制该对象。第一和第二引用内存中的同一对象。您可以向该类添加一个复制方法。