我没有太多使用泛型,因此无法弄清楚是否可以使用泛型将以下三种方法合二为一以减少重复。实际上我的代码目前有六种方法,但如果你能解决这三种方法,那么其余的应该都可以使用相同的解决方案。
private object EvaluateUInt64(UInt64 x, UInt64 y)
{
switch (Operation)
{
case BinaryOp.Add:
return x + y;
case BinaryOp.Subtract:
return x - y;
case BinaryOp.Multiply:
return x * y;
case BinaryOp.Divide:
return x / y;
case BinaryOp.Remainder:
return x % y;
default:
throw new ApplicationException("error");
}
}
private object EvaluateFloat(float x, float y)
{
switch(Operation)
{
case BinaryOp.Add:
return x + y;
case BinaryOp.Subtract:
return x - y;
case BinaryOp.Multiply:
return x * y;
case BinaryOp.Divide:
return x / y;
case BinaryOp.Remainder:
return x % y;
default:
throw new ApplicationException("error");
}
}
private object EvaluateDouble(double x, double y)
{
switch (Operation)
{
case BinaryOp.Add:
return x + y;
case BinaryOp.Subtract:
return x - y;
case BinaryOp.Multiply:
return x * y;
case BinaryOp.Divide:
return x / y;
case BinaryOp.Remainder:
return x % y;
default:
throw new ApplicationException("error");
}
}
我正在构建一个简单的表达式解析器,然后需要评估简单的二进制运算,例如加法/减法等。我使用上述方法来获取使用相关类型执行的实际数学运算。但必须有更好的答案!