[英]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.