我正在使用c#尝试使用随机数填充数据网格视图,但出于某种原因,我在所有单元格中都保持相同的值。
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();
}
}
}
答案 0 :(得分: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;
}
答案 1 :(得分:4)
使用时钟初始化Random,这意味着您将多次获得相同的值。
因此,不应重新创建Random实例,而应保留单个Random实例并继续在同一实例上使用Next。如果您有多个线程,那么您应该阅读this以获取锁定解决方案
这就是你需要的。
private Random random = new Random();
const int minimumNumber = -9;
const int maximumNumber = 15;
public int GenerateRandomNumber()
{
var randomNumber = random.Next(minimumNumber, maximumNumber);
return randomNumber;
}