在C#中,switch语句可以通过以下方法进行优化:
public enum ActionType
{
Add,
Subtract,
Multiply,
Divide
}
// 使用枚举
ActionType action = ActionType.Add;
switch (action)
{
case ActionType.Add:
// 添加操作
break;
case ActionType.Subtract:
// 减法操作
break;
case ActionType.Multiply:
// 乘法操作
break;
case ActionType.Divide:
// 除法操作
break;
default:
throw new ArgumentException("Invalid action type");
}
public delegate int Operation(int a, int b);
public static readonly Dictionary<string, Operation> operations = new Dictionary<string, Operation>
{
{ "add", (a, b) => a + b },
{ "subtract", (a, b) => a - b },
{ "multiply", (a, b) => a * b },
{ "divide", (a, b) => a / b }
};
// 使用字典
string operation = "add";
if (operations.TryGetValue(operation, out Operation op))
{
int result = op(1, 2);
}
else
{
throw new ArgumentException("Invalid operation");
}
public enum ActionType
{
Add,
Subtract,
Multiply,
Divide
}
// 使用模式匹配
ActionType action = ActionType.Add;
switch (action)
{
case ActionType.Add:
// 添加操作
break;
case ActionType.Subtract:
// 减法操作
break;
case ActionType.Multiply:
// 乘法操作
break;
case ActionType.Divide:
// 除法操作
break;
default:
throw new ArgumentException("Invalid action type");
}