列表通过for循环添加值后返回0 - c#

时间:2017-08-09 23:39:32

标签: c# list unity5

在此方法之后,我的列表计数返回0,而不应该。所有调试都是正确的,它们都不是null或其他东西。我正在使用Unity。 有谁知道问题在哪里?

List<Coordinates> FillCoordinates()
{
    List<Coordinates> coordinatesList = new List<Coordinates>();
    Debug.Log(minLenght);
    Debug.Log(maxLenght);
    Debug.Log(heights.Count);
    for (int i = minLenght; i > maxLenght; i++)
    {
        for (int j = 0; j < heights.Count; j++)
        {
            coordinatesList.Add(new Coordinates(i, heights[j]));
        }
    }

    return coordinatesList;
}

协调班级:

public class Coordinates
{
    public int lenght;
    public float height;

    public Coordinates(int lenght_, float height_)
    {
        lenght = lenght_;
        height = height_;
    }
}

2 个答案:

答案 0 :(得分:4)

我猜这永远不会执行,改变我&lt; maxLenght

    for (int i = minLenght; i > maxLenght; i++)
    {
        for (int j = 0; j < heights.Count; j++)
        {
            coordinatesList.Add(new Coordinates(i, heights[j]));
        }
    }

答案 1 :(得分:3)

@obl是对的,这不会执行:

for (int i = minLenght; i > maxLenght; i++)

for循环语句读取: &#34;从i minLength开始,当i大于maxLength时,运行循环,然后递增i。 #34;

由于我不比maxLength大,所以循环永远不会运行。

将其更改为:

for (int i = minLenght; i < maxLenght; i++)

&#34;从i minLength开始,当i小于maxLength时,运行循环,然后递增i }&#34;

它现在将从minLength一直运行到maxLength-1

你是对的,当i等于maxLength时,这不会最后一次运行循环。要解决这个问题(如果它真的是你想要的),只需按照以下方式进行调整:

for (int i = minLenght; i <= maxLenght; i++)

&#34;从i minLength开始,当i小于或等于maxLength时,运行循环,然后递增{ {1}}&#34;