【发布时间】:2014-04-06 16:13:23
【问题描述】:
正如标题所示,我正在通过循环初始化列表中的对象。但是当循环退出时,它们都变得相同。我可以在循环中看到它们不一样。但是当循环退出时,它们会变为最后输入的对象。
public List<ElevationLayout> layoutList = new List<ElevationLayout>();
public int layoutNumber { get; set; }
public int worldWidth { get; set; }
public Random seed { get; set; }
public XYSize dimLeft { get; set; }
//I have narrowed down the problem to this method
//==========================================================================================================================================================
//==========================================================================================================================================================
//==========================================================================================================================================================
public void init(World world) {
dimLeft = new XYSize();
ElevationLayout layout = new ElevationLayout();
dimLeft.y = 0;
dimLeft.x = world.size.x;
seed = new Random((int)DateTime.Now.Ticks);
worldWidth = (int)((world.size.x / 6.4) + (world.size.x / 64) - 1);
layoutNumber = worldWidth + seed.Next(-2, 3);
for (int i = 0; i < layoutNumber; i++)
{
layout.type = seed.Next(0, 2);
layout.width = (world.size.x / layoutNumber) + seed.Next(0, ((dimLeft.x / layoutNumber) / 2) + 1);
if (layout.width > dimLeft.x)
{
layout.width = dimLeft.x;
}
dimLeft.x -= layout.width;
layout.height = seed.Next(world.size.y / 16, (world.size.y / 4) + 1);
if (layout.height > dimLeft.y)
{
layout.height = dimLeft.y;
}
this.layoutList.Add(layout);
Console.Write(this.layoutList[i].type); // here the objects are different
if ((world.size.y -= layout.height) > dimLeft.y)
{
dimLeft.y = (world.size.y - layout.height);
}
if (dimLeft.x <= 0)
{
layoutNumber = i;
}
}
Console.WriteLine();
for (int y = 0; y < layoutNumber; y++)
Console.Write(this.layoutList[y].type); //but as soon as i exit the loop they are the same
}
//==============================================================================================================
//==============================================================================================================
//==============================================================================================================
这里有人遇到了类似的问题:Why is my list of objects all the same? 在这里:Why are all the values in my list the same?
最初我的对象列表是静态的,但后来我删除了它,问题仍然存在。
【问题讨论】:
标签: c#