您好,我是 WPF 新手,并且在 ASP.NET 方面确实有一些经验,但这完全是新的,就像标签一样,我会使用 label.Content
而不是 label.Text
,无论如何..我正在尝试做一个简单的表单,点击按钮后它会显示 5 个不同的随机数..
当我逐行调试此代码时,它确实随机化并具有一串不同的数字,但是当我不调试并立即运行它并单击按钮时,它会显示相同的数字吗? ,不知道为什么......所以理想情况下我会
[1] [23] [45] [24] [34]
如果我调试并单步执行,它会给我这个结果,但如果我不调试并只运行我得到的程序
[23] [23] [23] [23] [23]
任何帮助将不胜感激
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
int[] numbers = new int[5];
StringBuilder sb = new StringBuilder();
List<int> nums = new List<int>();
foreach (int i in numbers)
{
int rand = RandomNumber(1,59);
nums.Add(rand);
}
string numsList = string.Empty;
foreach (int items in nums)
{
numsList += "[" + items.ToString() + "]";
}
lblNumber.Content = numsList.ToString();
}
private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
}
}
最佳答案
您不应该每次都创建一个新的Random
(将其设为只读字段)。否则,当一个接一个地创建新实例时,种子可能始终相同。它仅在 Debug模式下工作,因为单步执行时实例的创建速度会更慢。
By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, while its parameterized constructor can take an Int32 value based on the number of ticks in the current time. However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers.
关于c# - 如何在 WPF 中进行随机化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8275649/