簡體   English   中英

遍歷列表時索引超出范圍異常<string>

[英]Index out of bounds exception while iterating through a List<string>

我有一個文件夾中圖像位置的列表。

我有五個pictureBoxes,它們模擬一個Coverflow類型區域,供用戶瀏覽給定文件夾的圖像。

我知道發生錯誤是因為集合中的第一個圖像設置為第一個圖片框,然后如果我單擊cycleLeft(),則為負數。

我該如何處理? 例如,如果“列表”中的第一張圖像已設置為最左側,並且有人單擊向左翻轉,則將第一張圖像放在列表的最后位置。

有指導嗎?

    private void leftArrow_Click(object sender, EventArgs e)
    {
        cycleImagesLeft();
    }

    private void rightArrow_Click(object sender, EventArgs e)
    {
        cycleImagesRight();
    }

    public void cycleImagesLeft()
    {
        //imageThree is the center image, that's why I use it as a frame of reference.
        int currentImage = pictures.IndexOf(imageThree.ImageLocation);
        imageOne.ImageLocation = pictures[currentImage - 3];
        imageTwo.ImageLocation = pictures[currentImage - 2];
        imageThree.ImageLocation = pictures[currentImage - 1];
        imageFour.ImageLocation = pictures[currentImage];
        imageFive.ImageLocation = pictures[currentImage + 1];
    }

    public void cycleImagesRight()
    {
        int currentImage = pictures.IndexOf(imageThree.ImageLocation);
        imageOne.ImageLocation = pictures[currentImage - 1];
        imageTwo.ImageLocation = pictures[currentImage];
        imageThree.ImageLocation = pictures[currentImage + 1];
        imageFour.ImageLocation = pictures[currentImage + 2];
        imageFive.ImageLocation = pictures[currentImage + 3];
    }

好吧,一種選擇是使用輔助方法來確保該值始終在范圍內:

string GetPictureAt(int index)
{
    // Copes with values which are two large or too small,
    // but only as far as -pictures.Length
    if (index < 0)
    {
        index += pictures.Length;
    }
    return pictures[index % pictures.Length];
}

然后:

public void CycleImagesLeft()
{
    int currentImage = pictures.IndexOf(imageThree.ImageLocation);
    imageOne.ImageLocation = GetPictureAt(currentImage - 3);
    imageTwo.ImageLocation = GetPictureAt(currentImage - 2);
    // etc
}

CycleImagesRight()相同。 認為這可以滿足您的要求,但是我不太理解您的倒數第二句話。

請注意,您仍然需要考慮少於5張圖片的可能性。

可以始終使用通告列表 至少以這種方式,所有索引管理資料都被抽象了(成為可測試和可重用的類)。

imageOne.ImageLocation = (currentImage - 3 < 0) ? null : pictures[currentImage - 3];
....
imageFour.ImageLocation = (currentImage + 2 >= pictures.Count) ? null : pictures[currentImage + 2];

等等

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM