C#Random.Next(min.max)返回值小于min

时间:2017-01-17 14:07:54

标签: c# random

有没有人知道为什么这段C#代码会返回x = 0y = 0(偶尔):

public void NewPos() 
{
    int x = 0;
    int y = 0;

    while (lstPosition.Where(z => z.Position.X == x && z.Position.Y == y).Count() != 0) {
        x = new Random().Next(4, 20) * 10;
        y = new Random().Next(4, 20) * 10;
    }

    NewPos.X = x;
    NewPos.Y = y; 

    Console.WriteLine(x + "  -  " + y );
}

2 个答案:

答案 0 :(得分:4)

虽然我们无法通过您提供的代码告知lstPosition设置了什么,但您并没有进入while循环。 where子句必须返回一个空集。

在这种情况下,Random.Next(int, int)无法返回零。

预计,您希望将xy初始化为非零值。

答案 1 :(得分:2)

你可能想要这样的东西:

// Do not recreate random 
// (otherwise you're going to have a badly skewed values); 
// static instance is the simplest but not thread safe solution
private static Random s_Generator = new Random();

public void NewPos() {
  // Just Any, not Where + Count
  if (lstPosition.Any(z => z.Position.X == x && z.Position.Y == y)) {
    // If we have such a point, resample it 
    NewPos.X = s_Generator.Next(4, 20) * 10;
    NewPos.Y = s_Generator.Next(4, 20) * 10; 

    // Debug purpose only
    Console.WriteLine(x + "  -  " + y ); 
  }
}