[英]C# Example Beginner
我正在尝试在3个不同的PictureBoxes中显示随机图像。 就像老虎机。 我将图像添加到图像列表。 但是,当我运行该程序时,我在所有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];
}
尝试这个。 将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);
}
因为在rand.Next(imageList1.Images.Count);
之后,您的index
将永远不会改变rand.Next(imageList1.Images.Count);
用rand.Next
分配index
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.