MST

星途 面试题库

面试题:C#模式匹配的复杂场景应用

假设你有一个包含不同类型图形(如圆形、矩形、三角形)的列表,且这些图形都继承自一个基类Shape。请使用C#的模式匹配技术,编写一个方法,计算列表中所有图形的总面积,要求充分利用模式匹配的优势来提高代码的可读性和可维护性。
49.5万 热度难度
编程语言C#

知识考点

AI 面试

面试题答案

一键面试
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}");
    }
}

在上述代码中:

  1. 定义了Shape基类,它有一个抽象方法Area用于计算图形面积。
  2. 分别定义了CircleRectangleTriangle类继承自Shape,并实现了Area方法。
  3. CalculateTotalArea方法使用模式匹配的switch表达式来根据不同的图形类型调用相应的Area方法,累加面积得到总面积。
  4. Main方法中创建了不同类型图形的实例并调用CalculateTotalArea方法计算总面积并输出。