接收任意数量的对象或对象数组的构造函数

Constructor that receives an arbitrary amount of objects or an array of objects

我有下一个任务: 添加接收任意数量的 Rectangle 类型对象或 Rectangle 类型对象数组的构造函数。

为了解决这个问题,我做了两个构造函数。但是,如果我根据问题的情况正确理解,它应该是一个构造函数。如何组合它们?还是不可能?

public ArrayRectangles(IEnumerable<Rectangle> rectangles)
    {
        rectangle_array = rectangles.ToArray();
    }

    public ArrayRectangles(Rectangle[] rectangle_array)
    {
        this.rectangle_array = new Rectangle[rectangle_array.Length];

        for (int i = 0; i < rectangle_array.Length; i++)
        {
            if (rectangle_array[i] != null)
            {
                this.rectangle_array[i] = new Rectangle(rectangle_array[i].GetSideA(), rectangle_array[i].GetSideB());
            }
        }
    }

您似乎在寻找 params 关键字:

By using the params keyword, you can specify a method parameter that takes a variable number of arguments. The parameter type must be a single-dimensional array.

public ArrayRectangles(params Rectangle[] rectangle_array)
{
    ...
}

允许使用 Rectangle 数组或可变数量的 Rectangle 参数调用方法(在本例中为 ctor):

var foo = new ArrayRectangles(new Rectangle[0]);
var bar = new ArrayRectangles(new Rectangle(), new Rectangle());