直接贴代码了:
static void Main(string[] args) { SwitchSample(); } private static void SwitchSample() { Switch(new Circle { Radius = 10 }); Switch(new Rectangle { Height = 10, Width = 10 }); Switch(new Rectangle { Height = 20, Width = 30 }); } private static void Switch(object o) { switch (o) { case Circle c: Console.WriteLine($"it's a circle with radius {c.Radius}"); break; case Rectangle r when (r.Width == r.Height): Console.WriteLine($"it's a square with width {r.Width}"); break; case Rectangle r: Console.WriteLine($"it's a rectangle with width {r.Width} and height {r.Height}"); break; default: break; } }
运行截图:
谢谢浏览!