C# 7 and higher versions
With the introduction of C# 7, it can be switched to realize the real type according to the mode match:
C# 6
switch(shape) { case Circle c: WriteLine($"圆形,半径为 {c.Radius}"); break; case Rectangle s when (s.Length == s.Height): WriteLine($"{s.Length} x {s.Height} 正方形"); break; case Rectangle r: WriteLine($"{r.Length} x {r.Height} 矩形"); break; default: WriteLine("<未知形状>"); break; case null: throw new ArgumentNullException(nameof(shape)); }
In C# 6, you can use the nameof () operator in the switch statement:
<> C# 5 and earlier versions
switch(o.GetType().Name) { case nameof(AType): break; case nameof(BType): break; }
Before C# 5, you can still simulate switching according to the type, but this requires a string containing the type name:
Which alternative to choose depends on the specific requirements of the application and the C# version used.The above is the detailed content of Are There Better Alternatives to Simulating a Switch on Type in C#?. For more information, please follow other related articles on the PHP Chinese website!