Is pattern matching better than traditional type-based switching?
In languages such as C# that do not support direct "switch by type", programmers usually use the classic "if...else if...else" structure to simulate type-based switching. However, as the number of types involved increases, this approach becomes lengthy and fragile.
Pattern Matching in C# 7 and later
Starting with C# 7, pattern matching provides a more elegant and concise way to switch by type. The "case type" syntax allows matching the types of variables, effectively replacing the "if" statement with a case of a specific pattern.
For example:
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# 6 using nameof()
In C# 6, you can use the nameof() operator to get the type name dynamically for switch statements. While not as concise as pattern matching, it provides an easier alternative to avoid hard-coded type names.
void Foo(object o)
{
switch (o.GetType().Name)
{
case nameof(A):
// 处理A类型
break;
case nameof(B):
// 处理B类型
break;
default:
// 处理其他类型
break;
}
}
Type-based switch in C# 5 and earlier
For C# 5 and earlier, you have no choice but to use the basic "if...else if...else" structure with hardcoded type names. This approach can become clumsy and error-prone.
void Foo(object o)
{
if (o is A)
{
// 处理A类型
}
else if (o is B)
{
// 处理B类型
}
else
{
// 处理其他类型
}
}
in conclusion
Pattern matching in C# 7 and later provides a powerful and concise way to simulate type-based switching. It eliminates the need for conditional chains, improves code readability, and reduces the possibility of errors. For earlier versions of C#, using nameof() and switch statements provided a more flexible alternative than hard-coded type names, while the classic "if...else if...else" structure is still a less ideal but still viable option.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3