简体   繁体   English

随机 x 和 y position

[英]Random x and y position

Only thing i want is to pick a random X position and random Y position我唯一想要的是选择一个随机的 X position 和随机的 Y position

Random x = new Random(255);
Random y = new Random(255);
int xp = x.Next(0, 255);
int yp = y.Next(0,255);

compile time Error:编译时错误:

Error: CS0236 A field initializer cannot reference the non-static field, method, or property 'Protivnik.x'错误:CS0236 字段初始值设定项无法引用非静态字段、方法或属性“Protivnik.x”

Error: CS0236 A field initializer cannot reference the non-static field, method, or property 'Protivnik.y'错误:CS0236 字段初始化程序无法引用非静态字段、方法或属性“Protivnik.y”

Can anyone explain me why is this happening?谁能解释我为什么会这样?

You can use that:你可以使用它:

static class Program
{

  static Random random = new Random(255);

  static void Main(string[] args)
  {
    int posX = random.Next(0, 255);
    int posY = random.Next(0, 255);
    ...
  }

}

Beware that Next upper bound is excluded, so here it generates [0..254].注意 Next 上限被排除在外,所以这里它生成 [0..254]。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM