将bool比较运算符放入变量中
本文关键字:变量 运算符 bool 比较 | 更新日期: 2023-09-27 18:18:13
我想重构以下代码:
switch (str)
{
case "<":
return value1 < value2;
case ">":
return value1 > value2;
case "<=":
return value1 <= value2;
case ">=":
return value1 >= value2;
case "==":
return value1 == value2;
case "!=":
return value1 != value2;
}
我想把布尔比较运算符放在变量中,然后只使用一次,像这样:
BoolOperator op;
switch (str)
{
case "<":
op = BoolOperator.Less;
break;
case ">":
op = BoolOperator.Greater;
break;
case "<=":
op = BoolOperator.LessOrEqual;
break;
case ">=":
op = BoolOperator.GreaterOrEqual;
break;
case "==":
op = BoolOperator.Equal;
break;
case "!=":
op = BoolOperator.NotEqual;
break;
}
return value1 op value2;
有办法做到这一点吗?
一个解决方案是使用委托和一些lambda函数:
public static bool Compare<T>(T value1, T value2, string str) where T : IComparable<T>
{
Func<T, T, bool> op = null;
switch (str)
{
case "<":
op = (a, b) => a.CompareTo(b) < 0;
break;
case ">":
op = (a, b) => a.CompareTo(b) > 0;
break;
case "<=":
op = (a, b) => a.CompareTo(b) <= 0;
break;
case ">=":
op = (a, b) => a.CompareTo(b) >= 0;
break;
case "==":
op = (a, b) => a.CompareTo(b) == 0;
break;
case "!=":
op = (a, b) => a.CompareTo(b) != 0;
break;
default:
throw new ArgumentException();
}
return op(value1, value2);
}