Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 试图避免两次显示同一图像_C#_Winforms_Picturebox - Fatal编程技术网

C# 试图避免两次显示同一图像

C# 试图避免两次显示同一图像,c#,winforms,picturebox,C#,Winforms,Picturebox,我使用图片框显示图像,并以1秒为间隔计时。我试图避免连续两次显示相同的图像,并使用arraylist来避免相同的随机图像依次显示 这就是我所做的。工作不如我预期的那么好,最终得到了一个例外。 如何改进此功能以避免连续两次显示同一图像 Random random = new Random(); ArrayList imagesList = new ArrayList(); Image[] images = { imageOne, imageTwo, imageThr

我使用图片框显示图像,并以1秒为间隔计时。我试图避免连续两次显示相同的图像,并使用arraylist来避免相同的随机图像依次显示

这就是我所做的。工作不如我预期的那么好,最终得到了一个例外。 如何改进此功能以避免连续两次显示同一图像

Random random = new Random();
        ArrayList imagesList = new ArrayList();
        Image[] images = { imageOne, imageTwo, imageThree, imageFour, imageFive, imageSix, imageSeven };

        do
        {
            try
            {
                for (int i = 0; i < images.Length; i++)
                {

                    imagesList.Add(images[random.Next(0, 7)]);

                    while (imagesList.Contains(images[i]))
                    {
                        imagesList.Clear();
                        imagesList.Add(images[random.Next(0, 7)]);     

                    }
                    picImage.Image = (Image)imagesList[0];

                }

                Thread.Sleep(1000);
            }
            catch (IndexOutOfRangeException ind)
            {
                MessageBox.Show(ind.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception exe)
            {
                MessageBox.Show(exe.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


        } while (true);
    }
Random Random=new Random();
ArrayList imagesList=新的ArrayList();
Image[]images={imageOne,imageTwo,imageThree,imageFour,imageFive,imageSix,imageSeven};
做
{
尝试
{
对于(int i=0;i
您可以进行随机洗牌,而不是随机数。这样,您就不必每次都检查图像是否已被使用。查看此处以了解如何洗牌数组:。现在你可以在数组中循环,它现在是随机的,你不会得到重复的


我猜你用睡眠来避免每次都得到相同的随机值?你现在可以删除它。除此之外,它还会阻塞用户界面。

只需重新排列图像即可:

Image[] randomOrder = images.OrderBy(i => Guid.NewGuid()).ToArray();
并遍历该数组

您还需要使用计时器来更改图像,因为您当前正在阻止UI线程<代码>系统.窗口.窗体.计时器将是合适的。计时器的
勾选事件处理程序如下所示:

private int index = 0;

private void Timer_Tick(Object sender, EventArgs args) 
{
  picImage.Image = randomOrder[index % randomOrder.Length];
  index++;
}

计时器
类的示例代码也很有用。请注意,框架中有几个可用的
Timer
类,这个类可能是这里最好的。

不是答案,只是一个改进提示:我不会在代码中使用
Thread.Sleep
。您将阻塞UI,刷新图片,然后再次阻塞。在本例中,我将使用计时器来使UI可用:)以改进代码-删除
睡眠
,以更少的空间改进问题格式示例,并提供有关所面临错误的信息。也许可以指定“一,二,一,二,一,二,一”是可以接受的,或者你希望所有的值都存在,但是被洗牌(洗牌可能是这个问题的好搜索词)。我猜他的问题是random可以显示相同值的两倍。你能做一个数组吗?然后您可以一次循环浏览所有图像。没有随机性。这是你想要的吗?