0

我正在使用 c# 尝试使用随机数填充 datagridview,但由于某种原因,我在所有单元格中始终获得相同的值。

    public int GenerateRandomNumber()
    {
        const int minimumNumber = -9;
        const int maximumNumber = 15;
        var random = new Random();
        var randomNumber = random.Next(minimumNumber, maximumNumber);
        return randomNumber;
    }

gameBoard 是数据网格视图。

    private void populateButton_Click(object sender, EventArgs e)
    {
        CreateGameBoard((int)columnsNumericUpDown.Value,(int)rowsNumericUpDown.Value);
        gameBoard.RowTemplate.Height = gameBoard.Height/gameBoard.RowCount;
        foreach (DataGridViewRow row in gameBoard.Rows)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {

                cell.Value = GenerateRandomNumber();
            }
        }
    }
4

2 回答 2

5

不要重新创建随机生成器:

// Random generator, one instance for the loop, no re-creation 
private m_Random = new Random();
...
public int GenerateRandomNumber()
{
    const int minimumNumber = -9;
    const int maximumNumber = 15;

    // Do not re-create random generator! Use single instance instead
    //var random = new Random();
    var randomNumber = m_Random.Next(minimumNumber, maximumNumber);
    return randomNumber;
}
于 2013-09-02T06:09:34.197 回答
4

Random 使用时钟初始化,这意味着您将多次获得相同的值。

因此,您应该保留一个 Random 实例并继续在同一个实例上使用 Next,而不是重新创建 Random 实例。如果您有多个线程,那么您应该阅读锁定解决方案

这就是你需要的。

private Random random = new Random();
const int minimumNumber = -9;
const int maximumNumber = 15;
public int GenerateRandomNumber()
{        
    var randomNumber = random.Next(minimumNumber, maximumNumber);
    return randomNumber;
}
于 2013-09-02T06:11:47.957 回答