c# - 如何在 WPF 中进行随机化

标签 c# wpf

您好,我是 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模式下工作,因为单步执行时实例的创建速度会更慢。

MSDN:

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/

相关文章:

c# - WPF:动画线减慢 UI

c# - WPF 组合框 : Wrong Item is displayed

c# - 如何在DataGridTextColumn中获取文本像素大小

c# - TreeNode 鼠标悬停工具提示未显示

c# - MVVMCross MvxBind,将多个值绑定(bind)到一个属性

c# - 带有模式的 Switch 语句

wpf - 将嵌套的用户控件绑定(bind)到复合 View 模型

WPF - 使用 View 模型数据进行复制/粘贴与拖放时内存不足

c# - 写入文件时 Json.net 异步

c# - .NET 核心 Entity Framework - 转义 "@"字符