求问一道 C#笔试题,想知道最好的解答是什么
题目如下:
这是一段用于计算多个几何形状面积之和的程序
- 指出程序段存在的不妥之处,并重构代码
- 在 1 的基础上增加一种可计算的几何形状类型三角形,其面积为 底×高×1/2
public class Shape { public int Type { get; set; } public int Radius { get; set; } public int Width { get; set; } public int Length { get; set; } } public class ShapeCalculator { public static double CalculateTotalArea(List<Shape> shapes) { double totalArea = 0; if (shapes != null && shapes.Count() > 0) { foreach (Shape shape in shapes) { if (shape.Type == 1) { totalArea += Math.PI * shape.Radius * shape.Radius; } else if (shape.Type == 2) { totalArea += shape.Length * shape.Width; } } } return totalArea; } }
我的回答是这样的:
interface ICalc { double GetAera(); } class Circle : ICalc { public int Radius { get; set; } public double GetAera() { return Math.PI * Radius * Radius; } } class Rectangle : ICalc { public int Length { get; set; } public int Width { get; set; } public double GetAera() { return Length * Width; } } class Triangle : ICalc { public int Bottom { get; set; } public int Height { get; set; } public double GetAera() { return Bottom * Height * 0.5; } } class ShapeCalculator { public static double CalculateTotalArea(List<ICalc> shapes) { double totalArea = 0; if (shapes != null) { totalArea = shapes.Sum(shape => shape.GetAera()); } return totalArea; } }
凭我的水平和理解能力就只有写到这种程度了……有什么更好的写法吗?