当我编辑一个实例的变量值时,其他实例也会发生变化

时间:2014-09-09 18:41:09

标签: c# class variables linked-list

我有两个班级,' Unit'和' Tile'。这两个都有一个位置'他们这样的课程就像......

class Unit
{
    // add the stats like name , health, speed and strength.
    public Stats stats = new Stats();

    // add the location coordinates
    public Location location = new Location();
}

public class Tile
{
    // add the stats like name , health, speed and strength.
    public Stats stats = new Stats();

    // represents the ability to move out of tile via either {north,east,south,west};
    public List<bool> movementDirections = new List<bool>() { true, true, true, true };

    // represents the Coorinates to access the tile.
    public Location location = new Location();
}
好的,所以......你会注意到我也有“统计数据”和#39;两个人都上课。两个&#39;单位&#39;和&#39; Tile&#39;是新的实例,并且都有新的实例&#39;统计数据&#39;和&#39;位置&#39;在他们身上。

我的问题是我有一小段代码可以改变单位的位置,而且行为奇怪。

        static void move(Tile tile,int[] coordsChange,Unit unit)
    {
        // Unit player is defined earlier in the script as a new Unit().
        player.stats.name = "Hendry";// just to check. this doesn't change the tile name
        player.location.x = player.location.x + coordsChange[0]; // these both change the tile location also.
        player.location.y = player.location.y + coordsChange[1];
    }

因为所有内容都是一个新实例并且玩家统计数据的更改并未改变Tile统计数据我不知道为什么但是玩家的位置发生了变化。我也测试了反之亦然,同样的情况发生了......就好像位置类是相关联的,但是尽管没有差别,但统计类没有。

这是BTW课程。

public class Location
{
    private int _x = 0;
    private int _y = 0;

    public int x
    {
        get { return _x; }
        set { _x = value;}
    }

    public int y
    {
        get { return _y;}
        set { _y = value; }
    }
}

public class Stats
{
    public string name = "default";
    public string className = "default";
    public int health = 10;
    public int strength = 5;
    public int defence = 5;
    public int speed = 5;
    public int intelligence = 5;
}

任何想法都会受到赞赏。

由于      zorilya

1 个答案:

答案 0 :(得分:-1)

封装的重要性:

class Unit
{
    // add the stats like name , health, speed and strength.
    public Stats stats { get; private set; }
    // add the location coordinates
    public Location location { get; private set; }

    public Unit()
    {
        location = new Location();
        stats = new Stats();
    }

}

Tile相同。

<强>更新

我的理论是,在调用move之前,你有代码分配:

player.location = tile.location;

tile.location = player.location;

使用私有setter使location属性生成,将导致此类代码出现编译错误。

<强>更新

public class Location
{
    ...
    your code
    ...

    public void Assign(Location aSource)
    {
        x = aSource.x;
        y = aSource.y;
    }
}

tile.location.Assign(player.location);