Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 解析匹配运算符和重构开关案例_.net_Design Patterns_Refactoring_Switch Statement_Strategy Pattern - Fatal编程技术网

.net 解析匹配运算符和重构开关案例

.net 解析匹配运算符和重构开关案例,.net,design-patterns,refactoring,switch-statement,strategy-pattern,.net,Design Patterns,Refactoring,Switch Statement,Strategy Pattern,我需要一个将操作数/运算符作为参数并提供求值结果的函数。 我面临的问题是如何优雅地解析运算符 示例代码如下所示 internal static bool Evaluator(double operand1, double operand2, string operation) { bool evaluation = false; switch (operation) { case "<": evaluation = opera

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

示例代码如下所示

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;
}
内部静态布尔运算器(双操作数1、双操作数2、字符串运算)
{
布尔值=假;
开关(操作)
{
案例“”:
求值=操作数1>操作数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
公共静态函数解析操作(字符串操作)
{
开关(操作)
{
案例“”:
返回(x,y)=>x>y;

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

另一个解决您问题的好实现是注册表实现。这在这里起作用,因为规则总是相同的——将给定的键与操作相匹配。填写此抽象,用字典作为后盾。用您知道的操作预加载字典

public abstract class OperationRegistry
{
   public abstract void RegisterOperation(string symbol, Func<double, double, bool> operation);
   public abstract Func<double, double, bool> GetOperation(string symbol);
}
公共抽象类操作注册表
{
公共抽象无效注册表操作(字符串符号,Func操作);
公共抽象函数GetOperation(字符串符号);
}

FWIW,我更希望看到一个新类而不是Func,但可能这只是我自己。

非常接近,而且整洁。我看起来很相似,但我也想删除开关盒,以便稍后添加更多运算符。字典实现对我来说似乎很干净。关于Func,你是对的,一个新类更好。
public abstract class OperationRegistry
{
   public abstract void RegisterOperation(string symbol, Func<double, double, bool> operation);
   public abstract Func<double, double, bool> GetOperation(string symbol);
}