1

我正在寻找答案,但找不到任何东西,所以:

我正在制作简单的项目,但对此有疑问:

// fragment of code in parent form
Random r = new Random();
private void BeginGame()
    {
        SetName();
        sheep = new Sheep[howManySheep];
        for (int i = 0; i < howManySheep; i++)
            sheep[i] = new Sheep(this);
        (...)
    }

public Sheep DrawSheep
    {
        set
        {
            splitContainer1.Panel2.Controls.Add(value);
        }
    }
// fragment of code in child form
 class Sheep : Button
 public Sheep(Form1 _parent)
        : base()
    {
        var p = new Point(r.Next(_parent.PanelSize[0]), r.Next(_parent.PanelSize[1]));
        Text = null;
        Size = new Size(size, size);
        BackColor = Color.White;
        Tag = nrSheep++;
        Location = p;
        _parent.DrawSheep = this;
        MessageBox.Show(this.Location.ToString());
    }

当 MessageBox.Show(..) 被注释时,它只画了一只羊(我的意思是所有的羊,但在同一个地方) 当 MessageBox.Show(..) 没有注释时,它画的一切都很好,它应该是怎样的。我的问题是如何?

4

1 回答 1

0

这听起来像是一个相当普遍的问题Random。当您将其设为类级别变量时,它通常会消失:

public static Random r = new Random();

通常只需要一个Random生成器,这需要使其成为静态的。

但为什么会有MessageBox帮助?

Random当您快速连续创建新实例而不是保留单个静态实例时,最常出现问题。这可能发生得如此之快,以至于它们获得相同的默认种子,从当前时间派生,因此将创建相同的数字序列。

现在,显示 aMessageBox让新实例的创建之间有很多时间过去Random,所以问题似乎解决,但实际上只是隐藏了..

隐藏这个(和其他与时间相关的问题)的另一种更狡猾的方法是使用调试器 - 但不要让它阻止你使用它;-)

于 2014-08-25T17:56:44.593 回答