代码之家  ›  专栏  ›  技术社区  ›  Sergio Tapia

迭代列表时索引越界异常<string>

  •  0
  • Sergio Tapia  · 技术社区  · 14 年前

    我有一个文件夹中图像位置的列表。

    我有五个图片框模拟CoverFlow类型的区域,供用户浏览给定文件夹的图像。

    我知道这个错误被触发,因为集合中的第一个图像被设置为第一个PictureBox,然后如果我单击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];
        }
    
    3 回复  |  直到 14 年前
        1
  •  2
  •   Jon Skeet    14 年前

    好吧,一个选项是使用helper方法来确保该值始终在界限内:

    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张图片。

        2
  •  1
  •   Roman    14 年前

    可以始终使用 Circular List . 至少这样,所有的索引管理内容都被抽象出来(抽象成一个可测试的、可重用的类)。

        3
  •  0
  •   BlueRaja - Danny Pflughoeft    14 年前
    imageOne.ImageLocation = (currentImage - 3 < 0) ? null : pictures[currentImage - 3];
    ....
    imageFour.ImageLocation = (currentImage + 2 >= pictures.Count) ? null : pictures[currentImage + 2];
    

    等。