将布尔比较运算符放

将布尔比较运算符放

本文介绍了将布尔比较运算符放在变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重构以下代码:

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

我想将布尔比较运算符放入变量中,然后仅使用一次,如下所示:

I would like to put boolean comparison operator in variable and then use it only once, something like this:

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;

有什么办法可以做到这一点?

Is there any way to achieve this?

推荐答案

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

One solution would be to use a delegate and some lambdas functions :

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

这篇关于将布尔比较运算符放在变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 00:31