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



有没有人知道为什么这段 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 );
}

你永远不会进入while循环,尽管我们无法知道你提供的代码lstPosition设置了什么。where 子句必须返回空集。

在这种情况下,Random.Next(int, int) 不可能返回零。

据推测,您希望启动xy为非零值。

您可能想要这样的东西:

// 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 ); 
  }
}

最新更新