c# - 如何使用开闭原理 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();
解决方案
您需要创建矩形对象并设置它们的高度和宽度以进行计算。如果不是, _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() 方法。希望有帮助。
推荐阅读
- r - gregexpr - 如何维护在 r 中提取的数字列表的顺序
- php - set a variable that holds array from a function
- python - 根据它们之间的接近度创建坐标列表
- php - Laravel 查询结果无法正确显示在刀片上
- javascript - 我想在 CYPRESS 的 datepicker 和 timepicker 中提前 8 天 8 小时选择日期和时间
- angular - Angular 服务器端渲染不断回到 502 错误
- javascript - 刷新页面后保持切换隐藏/显示
- javascript - Discord bot,当在频道中发送消息时赋予人一个角色,javascript
- node.js - 如何使用mongodb计算flutter中的工作时间
- gis - USGS LIDAR 数据中的“Z”值或“高程”值使用什么单位?