如何使用开放闭合原理C#计算面积

问题描述 投票:0回答:1

我正在使用C#中的SOLID的开闭原理。我有抽象类Shape,我想用它来计算不同形状的面积。如何调用areaCalculator类以及如何传递不同的形状。这是我的代码。

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

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

public class AreaCalculator
{
    public double TotalArea(Shape[] shapes)
    {
        double area = 0;
        foreach (var objShapes in shapes)
        {
            area += objShapes.Area();
        }
        return area;
    }
}

我想调用areaCalculator类来计算面积。

AreaCalculator _obj = new AreaCalculator();
            Shape[] _shapes = new Shape[2];
            var _result = _obj.TotalArea(_shapes);
            Console.WriteLine(_result);
            Console.ReadLine();
c# solid-principles open-closed-principle
1个回答
0
投票

您需要创建矩形对象并设置其高度和宽度以进行计算。如果不是,则_shapes列表为空。在下面找到工作代码示例。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShapesStacjOverflow {


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

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

    public class AreaCalculator {
        public double TotalArea(Shape[] shapes) {
            double area = 0;
            foreach (var objShapes in shapes) {
                area += objShapes.Area();
            }
            return area;
        }
    }
    class Program {
        static void Main(string[] args) {
            AreaCalculator _obj = new AreaCalculator();
            Shape[] _shapes = new Shape[2];
            Rectangle rectangle1 = new Rectangle {
                Width = 2,
                Height = 3
            };
            Rectangle rectangle2 = new Rectangle {
                Width = 1,
                Height = 1
            };
            _shapes[0] = rectangle1;
            _shapes[1] = rectangle2;

            var _result = _obj.TotalArea(_shapes);
            Console.WriteLine(_result);
            Console.ReadLine();
        }
    }
}

因此返回7。希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.