【发布时间】:2014-09-09 18:41:08
【问题描述】:
我有两个类,“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();
}
好的,所以...您会注意到我在两者上也都有“统计”类。 'Unit' 和 'Tile' 都是新实例,并且都有新的 'Stats' 和 'Location' 实例。
我的问题是我有一小段代码改变了单元的位置并且它的行为很奇怪。
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];
}
因为一切都是一个新的实例,玩家统计数据的变化并没有改变瓷砖统计数据,我不知道为什么,但玩家的位置发生了变化。我也测试了反之亦然,同样的情况发生了……就好像位置类是链接的,但统计类却没有,尽管它们没有区别。
顺便说一句,这里是那些类。
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;
}
任何想法都将不胜感激。
谢谢 佐里利亚
【问题讨论】:
-
播放器变量是什么?
-
您没有提供复制您的问题的示例。不知何故,在某个地方,您正在为两个字段分配对同一对象的引用,或者您没有正确观察您认为的行为。无论哪种方式,都没有足够的代码来重现问题。
-
“当我编辑一个实例的变量值时,另一个实例的值也发生了变化” - 那么它必须是同一个实体。
-
@HenkHolterman 他可能正在编辑这两个实体。他展示的代码没有,但他没有展示的代码可以。他也可能不正确地观察/打印结果,使得它们看起来相同(例如,由于不正确地关闭变量),即使它们实际上是不同的。无论如何,如果没有足够的代码来复制问题,猜测是没有意义的。
-
我没有打印结果,我正在使用 Visual Studio 调试并单步执行,从我向您展示的代码中看到它们同时发生变化......它们不一样如您所见,它们是用 new 关键字实例化的
标签: c# class variables linked-list