C#同时更新几个图片框

问题描述 投票:0回答:1

我的应用程序中有5个图片框,并且我同时更新了它们。我希望它们显示5个[[different图像,并且我的程序代码正确,但是由于某些原因,这些图片框会显示所有相同的图像...

这里是代码:

private System.Drawing.Bitmap DiceOne; private System.Drawing.Bitmap DiceTwo; private System.Drawing.Bitmap DiceThree; private System.Drawing.Bitmap DiceFour; private System.Drawing.Bitmap DiceFive; private System.Drawing.Bitmap DiceSix; public void Prepare() { for (int i = 0; i < 5; i++) Dices[i] = new Dice(); DiceOne = Properties.Resources.Würfel_1; DiceTwo = Properties.Resources.Würfel_2; DiceThree = Properties.Resources.Würfel_3; DiceFour = Properties.Resources.Würfel_4; DiceFive = Properties.Resources.Würfel_5; DiceSix = Properties.Resources.Würfel_6; } public void Roll() { foreach (Dice dice in Dices) dice.RollTheDice(); View.SuspendLayout(); View.diceOnePictureBox.Image = DiceNumberToBmp(Dices[0].GetLastRolled()); View.diceOnePictureBox.Update(); View.diceTwoPictureBox.Image = DiceNumberToBmp(Dices[1].GetLastRolled()); View.diceOnePictureBox.Update(); View.diceThreePictureBox.Image = DiceNumberToBmp(Dices[2].GetLastRolled()); View.diceOnePictureBox.Update(); View.diceFourPictureBox.Image = DiceNumberToBmp(Dices[3].GetLastRolled()); View.diceOnePictureBox.Update(); View.diceFivePictureBox.Image = DiceNumberToBmp(Dices[4].GetLastRolled()); View.diceOnePictureBox.Update(); View.ResumeLayout(false); } private System.Drawing.Bitmap DiceNumberToBmp(int number) { switch(number) { case 1: return DiceOne; case 2: return DiceTwo; case 3: return DiceThree; case 4: return DiceFour; case 5: return DiceFive; case 6: return DiceSix; default: return null; } }

[我以前在互联网上读过一些熟悉的帖子,并试图通过SuspendLayout,ResumeLayout,更新PictureBox进行解决。...对我来说什么都没用。

我的骰子班:

using System; namespace KniffelGUI.Model { public class Dice { private int LastRolled; public Dice() { RollTheDice(); } public Dice(int fakeRoll) { LastRolled = fakeRoll; } public int RollTheDice() { LastRolled = new Random().Next(6) + 1; return LastRolled; } public int GetLastRolled() { return LastRolled; } } }

c# bitmap picturebox
1个回答
0
投票
问题出在您的Dice类中,如Barry O'Kane先前所建议。

将其更改为:

public class Dice { private int LastRolled; private static Random R = new Random(); public Dice() { RollTheDice(); } public Dice(int fakeRoll) { LastRolled = fakeRoll; } public int RollTheDice() { LastRolled = R.Next(6) + 1; return LastRolled; } public int GetLastRolled() { return LastRolled; } }

您的症状是由于以下原因而发生:\

LastRolled = new Random().Next(6) + 1;

当您使用默认构造函数创建Random实例时,它将使用当前时间作为种子。当您快速连续创建多个实例时,它们以相同的种子结束,因此不会得到不同的数字。

通过声明为静态,类的所有实例将使用相同的Random实例,并且在每次调用时获得不同的编号。

© www.soinside.com 2019 - 2024. All rights reserved.