我还没有使用过泛型,所以无法弄清楚是否可以将以下三种方法变成一种使用泛型来减少重复的方法。其实我的代码目前有六种方法,但如果你可以解决这三个问题,那么剩下的就可以用同样的解决方案工作。如何将这3种方法变成一种使用C#泛型的方法?
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");
}
}
我建立一个简单的表达式解析器,则需要评估的简单的二进制运算,如加法/减法等我用上面的方法来获取实际的数学使用相关的类型进行。但是必须有更好的答案!
与流行的猜测相反,Marc和我实际上是两个不同的人。我们似乎偶尔分享一下心灵。 – 2008-10-05 08:17:04
也许我们只是认为......曾经见过搏击俱乐部? – 2008-10-05 08:20:27