简体   繁体   English

C#示例初学者

[英]C# Example Beginner

I'm trying to display in 3 different PictureBoxes random images. 我正在尝试在3个不同的PictureBoxes中显示随机图像。 Like a slot Machine. 就像老虎机。 I added my images to an imagelist. 我将图像添加到图像列表。 When i run the program however, I keep getting the exact same pictures in all 3 boxes. 但是,当我运行该程序时,我在所有3个框中始终得到完全相同的图片。 Any help is greatly appreciated. 任何帮助是极大的赞赏。 Here is my code snipet. 这是我的代码片段。

 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];
  }

Try this. 尝试这个。 Put the initialization of Random in the global scope. 将Random的初始化置于全局范围内。 Now it doesn't need to recreate the object each time you call Next. 现在,无需每次调用​​Next都重新创建对象。 It's faster and uses less memory. 它更快并且使用更少的内存。 It also prevents it from returning the same number, because Random uses the current time to generate numbers. 这也阻止了它返回相同的数字,因为Random使用当前时间生成数字。 If you keep recreating it and generating a number, it tends to return the same value repeatedly. 如果您继续创建它并生成一个数字,它往往会反复返回相同的值。

So last part: Make a function to get a random image index, this will make your code cleaner, and concise. 因此,最后一部分:创建一个函数以获取随机图像索引,这将使您的代码更简洁明了。 :) :)

Good luck man, programming is a great hobby. 祝你好运,编程是一个很大的爱好。 Hope it serves you well! 希望它能为您服务!

    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);
    }

Because your index will never changed after rand.Next(imageList1.Images.Count); 因为在rand.Next(imageList1.Images.Count);之后,您的index将永远不会改变rand.Next(imageList1.Images.Count);

Assign index with the rand.Next before every image rand.Next分配index

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM