MST

星途 面试题库

面试题:C#中模式匹配在switch表达式里的基础应用

假设你有一个包含不同形状(圆形、矩形、三角形)的几何图形类继承体系,基类为Shape,子类分别为Circle、Rectangle、Triangle。请使用C#的模式匹配和switch表达式来计算不同形状的面积。Shape类有一个抽象方法GetArea(),Circle类有半径radius属性,Rectangle类有width和height属性,Triangle类有baseLength和height属性。
36.6万 热度难度
编程语言C#

知识考点

AI 面试

面试题答案

一键面试
abstract class Shape
{
    public abstract double GetArea();
}

class Circle : Shape
{
    public double radius { get; set; }
    public override double GetArea()
    {
        return Math.PI * radius * radius;
    }
}

class Rectangle : Shape
{
    public double width { get; set; }
    public double height { get; set; }
    public override double GetArea()
    {
        return width * height;
    }
}

class Triangle : Shape
{
    public double baseLength { get; set; }
    public double height { get; set; }
    public override double GetArea()
    {
        return 0.5 * baseLength * height;
    }
}

class Program
{
    static void Main()
    {
        Shape[] shapes = new Shape[]
        {
            new Circle { radius = 5 },
            new Rectangle { width = 4, height = 6 },
            new Triangle { baseLength = 3, height = 8 }
        };

        foreach (var shape in shapes)
        {
            double area = shape switch
            {
                Circle circle => circle.GetArea(),
                Rectangle rectangle => rectangle.GetArea(),
                Triangle triangle => triangle.GetArea(),
                _ => throw new ArgumentException("Unsupported shape type")
            };
            Console.WriteLine($"The area of the {shape.GetType().Name} is {area}");
        }
    }
}