ホームページ  >  記事  >  バックエンド開発  >  C# 7.0 のパターン マッチングとは何ですか?

C# 7.0 のパターン マッチングとは何ですか?

WBOY
WBOY転載
2023-09-17 12:09:031400ブラウズ

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

C# 7.0 では、is 式と switch という 2 つの状況でのパターン マッチングが導入されています。 声明。

パターンは、値が特定の形状を持ち、次から取得できるかどうかをテストします。 形状が一致している場合の値です。

パターン マッチングは、アルゴリズムのよりクリーンな構文を提供します

任意のデータ型 (独自のデータ型でも) に対してパターン マッチングを実行できます。 そうでなければ、常に一致するプリミティブが必要です。

パターン マッチングでは、式から値を抽出できます。

パターン一致前 -

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

以上がC# 7.0 のパターン マッチングとは何ですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はtutorialspoint.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。
前の記事:C# 数のブースト次の記事:C# 数のブースト