Lai*_*uan 4 c# random ienumerable
我有一个类Rectangle,其中有一个方法RandomPoint返回其中的随机点.看起来像:
class Rectangle {
int W,H;
Random rnd = new Random();
public Point RandomPoint() {
return new Point(rnd.NextDouble() * W, rnd.NextDouble() * H);
}
}
Run Code Online (Sandbox Code Playgroud)
但我希望它是一个IEnumerable<Point>可以使用的LINQ,例如rect.RandomPoint().Take(10).
如何简洁地实现它?
Mar*_*ers 12
您可以使用迭代器块:
class Rectangle
{
public int Width { get; private set; }
public int Height { get; private set; }
public Rectangle(int width, int height)
{
this.Width = width;
this.Height = height;
}
public IEnumerable<Point> RandomPoints(Random rnd)
{
while (true)
{
yield return new Point(rnd.NextDouble() * Width,
rnd.NextDouble() * Height);
}
}
}
Run Code Online (Sandbox Code Playgroud)
IEnumerable<Point> RandomPoint(int W, int H)
{
Random rnd = new Random();
while (true)
yield return new Point(rnd.Next(0,W+1),rnd.Next(0,H+1));
}
Run Code Online (Sandbox Code Playgroud)