温馨提示×

c# switch支持哪些类型

c#
小樊
81
2024-12-01 05:09:05
栏目: 编程语言

C# 中的 switch 语句支持以下几种类型:

  1. 字符串(string):这是最常用的 switch 类型,可以对字符串进行比较。
string input = "apple";

switch (input)
{
    case "apple":
        Console.WriteLine("It's an apple.");
        break;
    case "banana":
        Console.WriteLine("It's a banana.");
        break;
    default:
        Console.WriteLine("Unknown fruit.");
        break;
}
  1. 整数(int、short、byte、sbyte):可以对整数进行比较,支持范围检查。
int number = 2;

switch (number)
{
    case 1:
        Console.WriteLine("Number is one.");
        break;
    case 2:
        Console.WriteLine("Number is two.");
        break;
    case 3:
        Console.WriteLine("Number is three.");
        break;
    default:
        Console.WriteLine("Number is not 1, 2, or 3.");
        break;
}
  1. 枚举(enum):可以对枚举值进行比较。
enum Color
{
    Red,
    Green,
    Blue
}

Color color = Color.Red;

switch (color)
{
    case Color.Red:
        Console.WriteLine("Color is red.");
        break;
    case Color.Green:
        Console.WriteLine("Color is green.");
        break;
    case Color.Blue:
        Console.WriteLine("Color is blue.");
        break;
    default:
        Console.WriteLine("Unknown color.");
        break;
}
  1. 布尔值(bool):可以对布尔值进行比较。
bool isRaining = true;

switch (isRaining)
{
    case true:
        Console.WriteLine("It's raining.");
        break;
    case false:
        Console.WriteLine("It's not raining.");
        break;
    default:
        Console.WriteLine("Unknown weather.");
        break;
}
  1. 字节(byte)、短整型(short)、长整型(long):这些数值类型也可以用于 switch 语句。
byte value = 1;

switch (value)
{
    case 1:
        Console.WriteLine("Value is one.");
        break;
    case 2:
        Console.WriteLine("Value is two.");
        break;
    default:
        Console.WriteLine("Value is not 1 or 2.");
        break;
}
  1. 自定义类型:通过实现 IEquatable<T> 接口和重写 Equals() 方法,自定义类型也可以用于 switch 语句。
public class Person
{
    public string Name { get; set; }

    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
            return false;

        Person person = (Person)obj;

        return string.Equals(Name, person.Name);
    }

    public override int GetHashCode()
    {
        return Name.GetHashCode();
    }
}

Person person = new Person { Name = "Alice" };

switch (person)
{
    case Person p when p.Name == "Alice":
        Console.WriteLine("It's Alice.");
        break;
    case Person p when p.Name == "Bob":
        Console.WriteLine("It's Bob.");
        break;
    default:
        Console.WriteLine("Unknown person.");
        break;
}

0