c# - Windows 窗体应用程序 C# 发生了奇怪的事情

标签 c# winforms

我制作了一个简单的 WindowsFormsApplication,但我在使用它时遇到了一些困难。在表单中,我有 10 个文本框和一个按钮。该程序的目的是在我单击按钮时在每个框中生成不同的数字。这是代码的一部分:

private void button1_Click(object sender, EventArgs e)
    {
        int p = 0;
        int[] array = GeneratingArray();

        foreach (Control c in tableLayoutPanel1.Controls)
        {
            if (c.GetType().ToString() == "System.Windows.Forms.TextBox")
            {
                c.Text = array[p].ToString();
                p++;
            }
        }
    }

    public int GeneratingInt()
    {
        int random;
        Contract.Ensures(Contract.Result<int>() > -11, "Array out of Bounds(-10 ; 10)");
        Contract.Ensures(Contract.Result<int>() < 11, "Array out of Bounds(-10 ; 10)");
        Random gnr = new Random();
        random = gnr.Next(20);
        return random;
    }

    public int[] GeneratingArray()
    {
        int[] array = new int[10];
        int random;
        for (int i = 0; i < 10; i++)
        {
            random = GeneratingInt();
            array[i] = random;
        }

        return array;
    }

问题是,当我使用调试器时一切正常,但是当我启动应用程序时,所有框中都生成了相同的数字。我找不到导致这种问题的原因,所以我问你。谢谢。

最佳答案

问题是您的应用程序运行速度过快。

通过在每次调用 GeneratingInt 时创建一个新的 Random 实例,您可以用当前时间为随机数播种。在紧密循环中运行时,这会导致随机生成器每次都提供相同的数字。

将您的 Random 移动到类级别变量,构造一次,然后重用相同的实例。这将使它按照您希望的方式运行。

关于c# - Windows 窗体应用程序 C# 发生了奇怪的事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13895766/

相关文章:

winforms - ASP.Net 和 WinForms

c# - Post 方法在 ASP.NET Core 中不起作用

c# - 每当我打开 VS 2010 解决方案时,如何禁用正在 check out 的 .vspscc 文件?

c# - 单击标题时在 DataGridView 中获取 "Index was out of range"异常

c# - Visual Studio 设计器总是试图更改我的控件

C# Windows 窗体应用程序 - 从另一个线程和类更新 GUI?

c# - 以编程方式在 View 中创建列

c# - 如何使用 FileOpenDialog 在 C# 中打开文件

c# - Process.Start() 比在控制台中执行慢得多

c# - C# 中的双按位非(~~)