我使用 C# 版本 7.3,我想在此版本中使用双结果 = 操作开关,并且我的代码抛出错误 - 我该怎么办?
在 switch 语句上抛出错误。
有人可以帮助我吗?我会非常感激...
// Function for handling the arithmetic operations.
void PerformArithmetic(string operation)
{
double num1, num2;
Console.Write("Enter the first number: ");
while (!double.TryParse(Console.ReadLine(), out num1))
{
Console.Write("Invalid input. Please enter a valid number: ");
}
Console.Write("Enter the second number: ");
while (!double.TryParse(Console.ReadLine(), out num2))
{
Console.Write("Invalid input. Please enter a valid number: ");
}
double result = operation switch
{
"Addition" => num1 + num2,
"Subtraction" => num1 - num2,
"Multiplication" => num1 * num2,
"Division" => num2 != 0 ? num1 / num2 : double.NaN,
=> throw new InvalidOperationException("Unknown operation")
};
if (operation == "Division" && num2 == 0)
{
Console.WriteLine("Error: Division by zero is not allowed.");
}
else
{
Console.WriteLine($"Result of{operation}: {result}");
}
Console.WriteLine("Press any key to return to the calculation menu.");
Console.ReadLine();
}
Switch 表达式直到 C# 8 才存在,因此:要么更新编译器版本(从 2018 年 5 月开始已经明显过时),要么使用不同的语法。例如,一个 switch 语句:
double result;
switch (operation)
{
case "Addition":
result = num1 + num2;
break;
// ... etc
default:
throw new InvalidOperationException("Unknown operation");
}