不能用数组参数调用方法c#

Cant call method with array argument c#

我正在学习基于 SOLID 原则的教程,但我不明白如何实际实施此方法,这里是教程 Link

我无法理解代码的概念,但我不知道如何从我的 Main

中实际调用 AreaCalculator.Area 方法

如何调用计算矩形面积或圆形面积的方法?基于教程中的代码

Area(Circle with 10 radius);
Area(Rectangle with 10 width and 5 height);

Shape.cs

public abstract class Shape
{
    public abstract double Area();
}

Circle.cs

    public class Circle : Shape
    {
        public double Radius { get; set; }
        public override double Area()
        {
            return Radius * Radius * Math.PI;
        }
    }

Rectangle.cs

    public class Rectangle : Shape
    {
        public double Width { get; set; }
        public double Height { get; set; }
        public override double Area()
        {
            return Width * Height;
        }
    }

AreaCalculator.cs

public static double Area(Shape[] shapes)
        {
            double area = 0;
            foreach (var shape in shapes)
            {
                area += shape.Area();
            }

            return area;
        }

谢谢

var circle = new Circle { Radius = 10 };                  // Create a circle
var rectangle = new Rectangle { Width = 10, Height = 5 }; // Create a rectangle

var shapes = new Shape[] { circle, rectangle };           // Create array of shapes

double area = AreaCalculator.Area(shapes);                // Call Area method with array

如果只需要单个图形的面积,则AreaCalculator不需要;只需在单个形状上调用 Area 方法:

double circleArea = circle.Area();
double rectangleArea = rectangle.Area();

您需要实例化每个形状的实例并将它们作为数组传递给 AreaCalculator.Area() 方法。关键是 Area 方法将获取任何扩展 Shape.

的对象
var circle = new Circle();
circle.Radius = 5;

var rectangle = new Rectangle();
rectangle.Width = 10;
rectangle.Height = 3;

var area = AreaCalculator.Area(new Shape[] {circle, rectangle});

或者更简洁

AreaCalculator.Area(new Shape[]{
    new Circle() {Radius = 5},
    new Rectangle() {Width = 10, Height = 3}
});