【问题标题】:How to calculate area using Open closed principle C#如何使用开闭原理 C# 计算面积
【发布时间】:2020-04-08 05:57:08
【问题描述】:

我正在使用 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();

【问题讨论】:

  • 是什么让您认为您的代码违反了 OCP?您的实际问题是什么?
  • 我知道它不违反 OCP。但是我想调用areacalculator类怎么办呢?
  • 你正在调用那个类,你有什么问题?
  • 不知道怎么称呼。例如,我添加继承 Shape 的圆形类,然后计算哪个形状区域?
  • 这个问题与OCP或SOLID完全无关,只是你没有创建任何对象。下次提问时请多加注意。

标签: c# solid-principles open-closed-principle


【解决方案1】:

您需要创建矩形对象并设置它们的高度和宽度以进行计算。如果不是, _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() 方法。 希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多