Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.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# - Fatal编程技术网

C#示例初学者

C#示例初学者,c#,C#,我尝试在3个不同的图片框中显示随机图像。就像吃角子老虎机一样。我将图像添加到图像列表中。然而,当我运行该程序时,我会在所有3个框中得到完全相同的图片。非常感谢您的帮助。 这是我的密码 private void button1_Click(object sender, EventArgs e) { Random rand = new Random(); int index = rand.Next(imageList1.Images.Count); pictureB

我尝试在3个不同的图片框中显示随机图像。就像吃角子老虎机一样。我将图像添加到图像列表中。然而,当我运行该程序时,我会在所有3个框中得到完全相同的图片。非常感谢您的帮助。 这是我的密码

 private void button1_Click(object sender, EventArgs e)
 {
     Random rand = new Random();
     int index = rand.Next(imageList1.Images.Count);
     pictureBox1.Image = imageList1.Images[index];
     pictureBox2.Image = imageList1.Images[index];
     pictureBox3.Image = imageList1.Images[index];
  }

因为您的
索引在
rand.Next(imageList1.Images.Count)之后永远不会更改


rand分配
index
。在每个图像之前,下一个
尝试此操作。将Random的初始化放在全局范围内。现在,它不需要在每次调用Next时重新创建对象。它速度更快,占用的内存更少。它还防止返回相同的数字,因为Random使用当前时间生成数字。如果继续重新创建它并生成一个数字,它往往会重复返回相同的值

最后一部分:创建一个函数来获取随机图像索引,这将使您的代码更简洁明了。:)

祝你好运,编程是一项伟大的爱好。希望它能为您服务

    private readonly Random rand = new Random();
    private int[] _imgIndexes = new int[3];

    private void button1_Click(object sender, EventArgs e)
    {
        // generate the random index, and pick that image with that index, then store the index number in an array so we can compare the results afterwards.
        var randomIndex = getRandomImageIndex();
        pictureBox1.Image = imageList1.Images[randomIndex];
        _imgIndexes[0] = randomIndex;

        randomIndex = getRandomImageIndex();
        pictureBox2.Image = imageList1.Images[randomIndex];
        _imgIndexes[1] = randomIndex;

        randomIndex = getRandomImageIndex();
        pictureBox3.Image = imageList1.Images[randomIndex];
        _imgIndexes[2] = randomIndex;

        if (_imgIndexes[0] == _imgIndexes[1] && _imgIndexes[1] == _imgIndexes[2])
        {
            MessageBox.Show("same");
        }
        // reset the result array so we can compare again.
        _imgIndexes = new int[3];
    }

    private int getRandomImageIndex()
    {
        return rand.Next(imageList1.Images.Count);
    }

在设置每个图像之前,请执行
index=rand.Next(imageList1.Images.Count)
。问题是,您对所有图片框使用相同的随机数。这非常有帮助。非常感谢。如果我试着比较这些图像是否相同,就像吃角子老虎机一样,我会使用类似于。。。如果(picturebox1.Image==picturebox2.Image)有点像这样,我修改了答案,为您添加了这个。