C# 中的 switch
语句支持以下几种类型:
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}