C# how to use enum with switch
I can't figure out how to use switches in combination with an enum. Could you please tell me what I'm doing wrong, and how to fix it? I have to use an enum to make a basic calculator.
public enum Operator
{
PLUS, MINUS, MULTIPLY, DIVIDE
}
public double Calculate(int left, int right, Operator op)
{
int i = (int) op;
switch(i)
{
case 0:
{
return left + right;
}
case 1:
{
return left - right;
}
case 2:
{
return left * right;
}
case 3:
{
return left / right;
}
default:
{
return 0.0;
}
}
}
The end result should be something like this:
Console.WriteLine("The sum of 5 and 5 is " + Calculate(5, 5, PLUS))
Output: The sum of 5 and 5 is 10
Could you guys please tell me how I'm messing up?
You don't need to convert it
switch(op)
{
case Operator.PLUS:
{
}
}
By the way, use brackets
根本不要转换为int
switch(operator)
{
case Operator.Plus:
//todo
已经给出了正确的答案,但是这里是比开关更好的方法:
private Dictionary<Operator, Func<int, int, double>> operators =
new Dictionary<Operator, Func<int, int, double>>
{
{ Operator.PLUS, ( a, b ) => a + b },
{ Operator.MINUS, ( a, b ) => a - b },
{ Operator.MULTIPLY, ( a, b ) => a * b },
{ Operator.DIVIDE ( a, b ) => (double)a / b },
};
public double Calculate( int left, int right, Operator op )
{
return operators.ContainsKey( op ) ? operators[ op ]( left, right ) : 0.0;
}
链接地址: http://www.djcxy.com/p/84488.html
下一篇: C#如何使用开关的枚举