c# - 自定义随机可枚举?

标签 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);
    }
}

但我希望它是一个IEnumerable<Point>这样我就可以使用 LINQ在上面,例如rect.RandomPoint().Take(10) .

如何简洁的实现?

最佳答案

您可以使用迭代器 block :

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

关于c# - 自定义随机可枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13915676/

相关文章:

c# - 从另一个类 C# 访问窗体的控件

c# - 在 XAML 中为集合项设置转换器的位置

c - 我对如何解决这个警告和错误有点困惑

javascript - 用随机整数值填充数组

c# - 使用异常处理将 IEnumerable<Task<T>> 转换为 IObservable<T>

c# - Visual Studio和C#和Web开发人员生产力工具/帮助

c# - 自定义 PowerShell 管理单元 : custom format doesn't work

python - 将 Pandas 数据框拆分为互斥的子集

c# - 获取 IEnumerable 的第一项并将其余项作为 IEnumerable 返回,仅迭代一次

c# - 使用 Cast<T> 将 int[] 转换为 double[]?