Home > Backend Development > C++ > Are There Better Alternatives to Simulating a Switch on Type in C#?

Are There Better Alternatives to Simulating a Switch on Type in C#?

Barbara Streisand
Release: 2025-01-28 15:11:13
Original
854 people have browsed it

Are There Better Alternatives to Simulating a Switch on Type in C#?

Is there a better alternative to switching according to the type?

The code fragment provided is a common method that simulates the switching according to the type in C#. When the type cannot be actually switched according to the type because of the type relationship, this method can be used. However, in different scenarios, there may be several more suitable alternatives.

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));
}
Copy after login

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;
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template