在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");
}
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: C#静态方法是否线程安全