is句やswitch文を使う。
成果物
コード
is
C#6.0
if (shape is Square) { var s = (Square)shape; return s.Side * s.Side; }
C#7.0
if (shape is Square s) return s.Side * s.Side;
is
句に変数名を追加することで、その変数は指定した型へキャスト済みの値となる。
switch
public static double CalcArea(object shape) { switch (shape) { case Square s: return s.Side * s.Side; case Circle c: return c.Radius * c.Radius * Math.PI; case Rectangle r: return r.Height * r.Length; default: throw new ArgumentException( message: "shape is not a recognized shape", paramName: nameof(shape)); } }
switch文にオブジェクトを指定できるようになった。
when句
public static double ComputeArea_Version3(object shape) { switch (shape) { case Square s when s.Side == 0: case Circle c when c.Radius == 0: return 0; case Square s: return s.Side * s.Side; case Circle c: return c.Radius * c.Radius * Math.PI; default: throw new ArgumentException( message: "shape is not a recognized shape", paramName: nameof(shape)); } }
when
句を使えば条件指定できる。
他
caseにはnull
も使える。
case null: throw new ArgumentNullException(paramName: nameof(shape), message: "Shape must not be null");
var
を使って複雑な条件にもできる。
case var o when (o?.Trim().Length ?? 0) == 0: // white space return null;
対象環境
- Raspbierry pi 4 Model B
- Raspbian buster 10.0 2019-09-26 ※
- bash 5.0.3(1)-release
$ uname -a Linux raspberrypi 4.19.75-v7l+ #1270 SMP Tue Sep 24 18:51:41 BST 2019 armv7l GNU/Linux