面试题答案
一键面试using System;
using System.Collections.Generic;
// 基类Shape
public abstract class Shape
{
public abstract double Area();
}
// 圆形
public class Circle : Shape
{
public double Radius { get; set; }
public Circle(double radius)
{
Radius = radius;
}
public override double Area()
{
return Math.PI * Radius * Radius;
}
}
// 矩形
public class Rectangle : Shape
{
public double Width { get; set; }
public double Height { get; set; }
public Rectangle(double width, double height)
{
Width = width;
Height = height;
}
public override double Area()
{
return Width * Height;
}
}
// 三角形
public class Triangle : Shape
{
public double BaseLength { get; set; }
public double Height { get; set; }
public Triangle(double baseLength, double height)
{
BaseLength = baseLength;
Height = height;
}
public override double Area()
{
return 0.5 * BaseLength * Height;
}
}
class Program
{
public static double CalculateTotalArea(List<Shape> shapes)
{
double totalArea = 0;
foreach (var shape in shapes)
{
totalArea += shape switch
{
Circle circle => circle.Area(),
Rectangle rectangle => rectangle.Area(),
Triangle triangle => triangle.Area(),
_ => 0
};
}
return totalArea;
}
static void Main()
{
List<Shape> shapes = new List<Shape>
{
new Circle(5),
new Rectangle(4, 6),
new Triangle(3, 8)
};
double totalArea = CalculateTotalArea(shapes);
Console.WriteLine($"Total Area: {totalArea}");
}
}
在上述代码中:
- 定义了
Shape
基类,它有一个抽象方法Area
用于计算图形面积。 - 分别定义了
Circle
、Rectangle
和Triangle
类继承自Shape
,并实现了Area
方法。 CalculateTotalArea
方法使用模式匹配的switch
表达式来根据不同的图形类型调用相应的Area
方法,累加面积得到总面积。- 在
Main
方法中创建了不同类型图形的实例并调用CalculateTotalArea
方法计算总面积并输出。