将bool比较运算符放在变量中

时间:2015-10-19 08:44:40

标签: c# boolean

我想重构以下代码:

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;
}

我想将boolean比较运算符放在变量中,然后只使用一次,如下所示:

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;

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:0)

一种解决方案是使用委托和一些lambdas函数:

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);
}