C#7.0のパターンマッチングとは何ですか?
C#7.0では、is式とswitchstatementの2つのケースでパターンマッチングが導入されています。
パターンは、値が特定の形状を持っていることをテストし、一致する形状を持っている場合、値から情報を抽出できます。
パターンマッチングは、アルゴリズムのより簡潔な構文を提供します
独自のデータ型を含め、任意のデータ型でパターンマッチングを実行できますが、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
-
IPアドレスとは何ですか?
インターネットプロトコルアドレスの略であるIPアドレスは、ネットワークに接続されているネットワークハードウェアの識別番号です。 IPアドレスを持っていると、デバイスはインターネットなどのIPベースのネットワークを介して他のデバイスと通信できます。 IPアドレスはどのように見えますか? ほとんどのIPアドレスは次のようになります: 151.101.65.121 遭遇する可能性のある他のIPアドレスは、次のようになります。 2001:4860:4860::8844 IPアドレスは何に使用されますか? IPアドレスは、インターネット上のネットワークデバイスにIDを提供します。特
-
Windows 11 SE とは何ですか?
Chromebook と Chrome オペレーティング システムが教育市場をほぼ独占してきましたが、Microsoft はかなり長い間、競争の場に参入して平準化しようと試みてきました。 Windows 11 SE では、まさにそれを達成しようとしています。このオペレーティング システムは、K-8 クラスルームで作成されました 念頭に置いて。使いやすく、安全性が高く、機能が制限された低コストのコンピューターにより適していると考えられています。この新しい OS の開発中、Microsoft は教育者、学校の IT 担当者、および管理者と協力しました。 Windows 11 SE 用に特別に作成さ