C#is known for its multifunctionality, but it has always been a significant limitations that cannot be switched according to the type. However, with the emergence of new language versions, many alternative methods have emerged to avoid this limit.
C# 7 mode matching
C# 7 introduces mode matching, which is an elegant mechanism that allows switching directly according to the type. Consider the following example:
Mode matching provides a simple and type of security method to process different types in a Switch statement, thereby improving the readability of the code and promoting more effective specific types of operation.The nameof () operator in the c# 6
<code class="language-csharp">switch (shape) { case Circle c: WriteLine($"圆形,半径为 {c.Radius}"); break; // ... }</code>
For C# 6 users, the nameof () operator provides an alternative solution. By using the type name as a string as a target, you can build the Switch statement as shown below:
Although not as universal as mode matching, this method provides a reliable method for classifications in C# 6 and earlier versions.
C# 5 and earlier versions use the type name of the type name
<code class="language-csharp">switch (o.GetType().Name) { case nameof(AType): break; // ... }</code>
For users using C# 5 and below, the basic Switch statement using a hard -coding type name strings is still a feasible method, although the flexibility is low:
Although it lacks the complexity of its new corresponding objects, this method can still meet the simple type -based decision -making needs in the early version of C#.
The above is the detailed content of How Can I Achieve Superior Type-Based Control Flow in C#?. For more information, please follow other related articles on the PHP Chinese website!