【问题标题】:Parsing match operator and refactoring switch cases解析匹配运算符和重构 switch 案例
【发布时间】:2012-04-29 03:35:52
【问题描述】:

我需要一个将操作数/运算符作为参数并提供评估结果的函数。 我面临的问题是如何优雅地解析运算符。

示例代码如下

internal static bool Evaluator(double operand1, double operand2, string operation)
{
    bool evaluation = false;
    switch (operation)
    {
        case "<":
            evaluation = operand1 < operand2;
            break;

        case ">":
            evaluation = operand1 > operand2;
            break;

        case "<=":
            evaluation = operand1 <= operand2;
            break;

        default:
            break;
    }

    return evaluation;
}

我可以将运算符放在枚举(或可扩展枚举)中,并使用策略模式来删除开关盒。 问题仍然存在,我无法解析运算符。 例子

     op1="<";
     var operation = Operation.Parse(op1);
     var result = operand1 <--  operation should come here --> operand2.

请建议如何优雅地重构上述代码(Evaluator 函数)。

【问题讨论】:

    标签: .net design-patterns refactoring switch-statement strategy-pattern


    【解决方案1】:

    switch 语句是责任链模式的最简单实现,其目的是将您的问题路由到正确的处理程序。经典的 GoF 实现是链表。 Wikipedia 有一篇好文章,NetObjectives 也有。

    另一个很好的实现是注册表实现。这在这里有效,因为规则总是相同的——将给定的键与操作匹配。填写这个抽象,用字典支持它。用你知道的操作预加载字典。

    public abstract class OperationRegistry
    {
       public abstract void RegisterOperation(string symbol, Func<double, double, bool> operation);
       public abstract Func<double, double, bool> GetOperation(string symbol);
    }
    

    FWIW,我更希望看到一个新类而不是 Func,但也许这只是我。

    【讨论】:

    • 字典实现对我来说似乎很干净。关于 Func,你是对的,一个新的类更好。
    【解决方案2】:

    我想你可能正在寻找这样的东西:

    public static Func<double, double, bool> ParseOperation(string operation)
    {
        switch (operation)
        {
            case "<":
                return (x, y) => x < y;
    
            case ">":
                return (x, y) => x > y;
    
            case "<=":
                return (x, y) => x <= y;
    
            default:
                throw new Exception();
        }
    }
    

    你可以这样使用它:

    var op = ParseOperation("<");
    Console.WriteLine(op(1, 2)); // true
    

    【讨论】:

    • 非常接近,整洁。我正在寻找类似的东西,但我也想删除 switch-case 以稍后添加更多运算符。
    猜你喜欢
    • 2012-02-20
    • 2018-10-16
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多