如果或切换?以下哪一个是更简洁、更传统的代码?
If or switch? Which of these is a cleaner, more conventional code?
我了解到,如果可以使用 switch case,就应该使用它们,因为它们的性能更好。以下哪一个代码片段更常规?有多少行为完全相同的情况仍然适用于 switch 语句?您应该何时开始使用 if 语句?
Console.Write("Insert a card value: ");
int value = Int32.Parse(Console.ReadLine());
string symbol = "";
switch(value)
{
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 9:
case 10:
symbol = Convert.ToString(value);
break;
case 11:
symbol = "J";
break;
case 12:
symbol = "Q";
break;
case 13:
symbol = "K";
break;
case 14:
symbol = "A";
break;
}
Console.WriteLine("The " + symbol + " has a value of " + value);
或者这一个?
Console.Write("Insert a card value: ");
int value = Int32.Parse(Console.ReadLine());
string symbol = "";
if (value <= 10)
symbol = Convert.ToString(value);
else if (value == 11)
symbol = "J";
else if (value == 12)
symbol = "Q";
else if (value == 13)
symbol = "K";
else if (value == 14)
symbol = "A";
Console.WriteLine("The " + symbol + " has a value of " + value);
从 C#9 开始,有一个新的模式匹配,使开关具有很好的可读性:
string symbol = value switch
{
>=1 and <=10 => Convert.ToString(value),
11 => "J",
12 => "Q",
13 => "K",
14 => "A",
_ => ""
};
我了解到,如果可以使用 switch case,就应该使用它们,因为它们的性能更好。以下哪一个代码片段更常规?有多少行为完全相同的情况仍然适用于 switch 语句?您应该何时开始使用 if 语句?
Console.Write("Insert a card value: ");
int value = Int32.Parse(Console.ReadLine());
string symbol = "";
switch(value)
{
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 9:
case 10:
symbol = Convert.ToString(value);
break;
case 11:
symbol = "J";
break;
case 12:
symbol = "Q";
break;
case 13:
symbol = "K";
break;
case 14:
symbol = "A";
break;
}
Console.WriteLine("The " + symbol + " has a value of " + value);
或者这一个?
Console.Write("Insert a card value: ");
int value = Int32.Parse(Console.ReadLine());
string symbol = "";
if (value <= 10)
symbol = Convert.ToString(value);
else if (value == 11)
symbol = "J";
else if (value == 12)
symbol = "Q";
else if (value == 13)
symbol = "K";
else if (value == 14)
symbol = "A";
Console.WriteLine("The " + symbol + " has a value of " + value);
从 C#9 开始,有一个新的模式匹配,使开关具有很好的可读性:
string symbol = value switch
{
>=1 and <=10 => Convert.ToString(value),
11 => "J",
12 => "Q",
13 => "K",
14 => "A",
_ => ""
};