首页 > 解决方案 > 如何使用开闭原理 C# 计算面积

问题描述

我正在使用 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-principlesopen-closed-principle

解决方案


您需要创建矩形对象并设置它们的高度和宽度以进行计算。如果不是, _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。如果要创建其他子形状,则应覆盖 Area() 方法,因此对于列表中创建的每个对象,将应用相应的 Area() 方法。希望有帮助。


推荐阅读