// 此代码定义了一个形状类的层次结构,并演示了如何使用模式匹配与 switch 语句来确定每个形状的类型。

// Shape 类是所有形状的抽象基类。 // Square、Circle 和 Triangle 类继承自 Shape 类,并定义了自己的属性。

// Main 方法创建了一个 Shape 对象列表,并将 Circle、Square 和 Triangle 的实例添加到列表中。 // 它还添加了一个空 Square 对象,以演示模式匹配如何处理空值。

// foreach 循环遍历列表中的每个形状,并使用 switch 语句来确定每个形状的类型。

// switch 语句评估 shape 变量的类型和/或值。 // 如果形状是 Circle,则打印圆的半径。 // 如果形状是边长大于 10 的 Square,则打印它是一个大方形。 // 如果形状是常规 Square,则打印边长。 // 如果形状是 Triangle,则打印高度。 // 如果形状为空,则打印它可能是 Square、Circle 或 Triangle。 // 如果形状与任何情况都不匹配,则抛出 ArgumentException。

// 程序的输出将取决于列表中形状属性的值。

using System; using System.Collections.Generic;

public abstract class Shape { }

public class Square : Shape { public double Side { get; set; } }

public class Circle : Shape { public double Radius { get; set; } }

public class Triangle : Shape { public double Height { get; set; } }

class Program { static void Main() { var shapes = new List();

  shapes.Add(new Circle() { Radius = 7 });
  shapes.Add(new Square() { Side = 5 });
  shapes.Add(new Triangle() { Height = 4 });
  var nullSquare = (Square)null;
  shapes.Add(nullSquare);

  foreach (var shape in shapes)
  {
     switch (shape)                // 评估变量 shape 的类型和/或值。
     {
        case Circle circle:        // 等同于 if(shape is Circle)
           Console.WriteLine($'This shape is a circle of radius { circle.Radius }');
           break;

        case Square square when square.Side > 10: // 仅匹配 Square 的子集
           Console.WriteLine($'This shape is a large square of side { square.Side }');
           break;

        case Square square:
           Console.WriteLine($'This shape is a square of side { square.Side }');
           break;

        case Triangle triangle:    // 等同于 if(shape is Triangle)
           Console.WriteLine($'This shape is a triangle of side { triangle.Height }');
           break;

        // case Triangle triangle when triangle.Height < 5: // 编译错误
           // Console.WriteLine($'This shape is a triangle of side { triangle.Height }');
           //break;

        case null:
           Console.WriteLine($'This shape could be a Square, Circle or a Triangle');
           break;

        default:
           throw new ArgumentException(
           message: 'shape is not a recognized shape',
           paramName: nameof(shape));
     }
  }

} }

C# 逐行注释代码示例:使用模式匹配和 switch 语句识别形状

原文地址: https://www.cveoy.top/t/topic/ckW2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录