In the language that does not support "switching by type" in C#, programmers usually use classic "if ... else if ... else" structure to simulate type -based switching. However, as the number of types increases, this method will become lengthy and fragile.
C# 7 and the higher version mode match
From C# 7, the pattern matching provides a more elegant and more concise way to switch by type. The "Case Type" grammar allows the type of matching variables, and effectively replaces the "IF" statement in cases of specific mode. For example:
C# 6 Use nameof ()
In C# 6, you can use the nameof () computing symbol to dynamically obtain the type name for the Switch statement. Although it is not as simple as the pattern, it provides a more easy -to -reconstruction alternative to avoid hard -coding type names.
void Foo(object o) { switch (o) { case A a: // 匹配A类型 a.Hop(); break; case B b: // 匹配B类型 b.Skip(); break; default: throw new ArgumentException("意外类型: " + o.GetType()); } }
<> C# 5 and earlier version -based switching
For C# 5 and earlier versions, you have no choice but to use the basic "if ... else if ... else" structure with a hard -coding type name. This method may become awkward and easy to make mistakes.
void Foo(object o) { switch (o.GetType().Name) { case nameof(A): // 处理A类型 break; case nameof(B): // 处理B类型 break; default: // 处理其他类型 break; } }
Conclusion
C# 7 and the higher version mode matching provides a powerful and concise method of simulation -based switching. It eliminates the demand for the condition chain, improves the readability of code, and reduces the possibility of errors. For the early versions of C#, using Nameof () and Switch statements provided a more flexible alternative than hard -coding type name, and the classic "IF ... Else If ... Else" structure is still not ideal But still feasible choices.The above is the detailed content of Is Pattern Matching a Superior Alternative to Traditional Type-Based Switching in C#?. For more information, please follow other related articles on the PHP Chinese website!