-1

我使用一个简单的数组:包含字符串的 contentHouseOne[]。但是在 Do/While 循环中它不起作用!似乎代码不明白要创建新对象时它是一个字符串!?当我像下面显示的那样对字符串进行硬编码时,它会起作用。帮助是preciated!谢谢!

这不起作用:

listHouseParts.Add(new HousePart(content, contentHouseOne[i], newPosition));

但这有效:

 listHouseParts.Add(new HousePart(content, "100x100", newPosition));

编辑:

下面是一些声明数组的代码

string[] contentHouseOne = new string[] { "ruta100x100Red", 
                                          "ruta100x100Grey", 
                                          "ruta100x100Green", 
                                          "ruta100x100Yellow", 
                                          "ruta100x100Blue" };

bool[,] occupiedPositions = new bool[500,500];

这是一些将所有网格位置设置为 false 的代码

for (int i = 0; i < gridCol; i++)
    for (int ii = 0; ii < gridRow; ii++)
        occupiedPositions[i, ii] = false;

最后这是我遇到问题的代码

int i = 0;
do
{
    Vector2 newPosition = NewRandomPosition;
    if (occupiedPositions[(int)newPosition.X, (int)newPosition.Y] == false)
    {
        listHouseParts.Add(new HousePart(content, 
                                         contentHouseOne[i], newPosition));
        occupiedPositions[(int)newPosition.X, (int)newPosition.Y] = true;
        i++;
    }
}
while (i <= 5);
4

2 回答 2

4

您的字符串数组包含五个元素:

string[] contentHouseOne = new string[] { "ruta100x100Red",
                                          "ruta100x100Grey", 
                                          "ruta100x100Green", 
                                          "ruta100x100Yellow", 
                                          "ruta100x100Blue" };

但是while如果您的运行变量i大于 5 ,您的循环就会结束

while (i <= 5);

which causes a IndexOutOfBounds exception on contentHouseOne, because the 6th element at index 5 isn't defined. You should change your while condition to (i < 5).

于 2012-07-30T06:53:23.273 回答
0

试试这个,至少你知道它是否为空

    HousePart housePart = new HousePart();
    housePart.Content = content;

    if (!string.IsNullOrEmpty(contentHouseOne[i]))
        housePart.ContentHouseOne = contentHouseOne[i];
    else
        housePart.ContentHouseOne = string.Empty;

    housePart.NewPosition = newPosition;

    listHouseParts.Add(housePart);
于 2012-07-30T06:51:19.803 回答