什麼是 C# 7.0 中的模式匹配?


C# 7.0 在兩個情況下引入了模式匹配:is 表示式和 switch 語句。

模式測試一個值是否具有某種形狀,並且可以從值中提取資訊,當值具有匹配的形狀時。

模式匹配為演算法提供了更簡潔的語法

你可以對任何資料型別進行模式匹配,甚至是自己的資料型別,而使用 if/else,你需要始終使用原語進行匹配。

模式匹配可以從你的表示式中提取值。

在模式匹配之前

示例

public class PI{
   public const float Pi = 3.142f;
}
public class Rectangle : PI{
   public double Width { get; set; }
   public double height { get; set; }
}
public class Circle : PI{
   public double Radius { get; set; }
}
class Program{
   public static void PrintArea(PI pi){
      if (pi is Rectangle){
         Rectangle rectangle = pi as Rectangle;
         System.Console.WriteLine("Area of Rect {0}", rectangle.Width * rectangle.height);
      }
      else if (pi is Circle){
         Circle c = pi as Circle;
         System.Console.WriteLine("Area of Circle {0}", Circle.Pi * c.Radius * c.Radius);
      }
   }
   public static void Main(){
      Rectangle r1 = new Rectangle { Width = 12.2, height = 33 };
      Rectangle r2 = new Rectangle { Width = 12.2, height = 44 };
      Circle c1 = new Circle { Radius = 12 };
      PrintArea(r1);
      PrintArea(r2);
      PrintArea(c1);
      Console.ReadLine();
   }
}

輸出

Area of Rect 402.59999999999997
Area of Rect 536.8
Area of Circle 452.44799423217773

在模式匹配之後

示例

public class PI{
   public const float Pi = 3.142f;
}
public class Rectangle : PI{
   public double Width { get; set; }
   public double height { get; set; }
}
public class Circle : PI{
   public double Radius { get; set; }
}
class Program{
   public static void PrintArea(PI pi){
      if (pi is Rectangle rectangle){
         System.Console.WriteLine("Area of Rect {0}", rectangle.Width *
         rectangle.height);
      }
      else if (pi is Circle c){
         System.Console.WriteLine("Area of Circle {0}", Circle.Pi * c.Radius *
         c.Radius);
      }
   }
   public static void Main(){
      Rectangle r1 = new Rectangle { Width = 12.2, height = 33 };
      Rectangle r2 = new Rectangle { Width = 12.2, height = 44 };
      Circle c1 = new Circle { Radius = 12 };
      PrintArea(r1);
      PrintArea(r2);
      PrintArea(c1);
      Console.ReadLine();
   }
}

輸出

Area of Rect 402.59999999999997
Area of Rect 536.8
Area of Circle 452.44799423217773

更新於: 19-8-2020

269 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.