我有一个类:
class Entity
{
private String question;
private String answer;
private static int length;
Crosswords cr = new Crosswords();
public Entity(int posX, int posY, int direction)
{
length = cr.getSpaceLength(posX, posY, direction);
}
public int getLength()
{
return length;
}
}
在另一个类中,我创建了一个这样的实体数组:
Entity[] et = new Entity[100];
然后我有一个计算长度的算法,我想保存每个实体的长度,但在那之后,当我这样做时:
for(int i=0; i<100; i++)
Console.WriteLine(et[i].getLength());
我为所有实体设置了相同的长度(最后一个实体的长度),但我为它们设置了不同的长度。为什么会这样?我必须做什么才能为每个实体保存不同的长度?
附言
我这样创建实体:
for(int i=0; i<100; i++)
et[i] = new Entity(somevalueX, somevalueY, direction);
最佳答案
从长度中删除静态或更好地执行此操作,在需要时计算长度。
class Entity
{
private String question;
private String answer;
private int _posX;
private int _posY;
private int _direction;
Crosswords cr = new Crosswords();
public Entity(int posX, int posY, int direction)
{
_posX = posX;
_posY = posY;
_direction = direction;
}
public int getLength()
{
return cr.getSpaceLength(_posX, _posY, _direction);
}
}
关于C#保存多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28318010/