C#中如何使用枚举带开关 [英] C# how to use enum with switch

查看:173
本文介绍了C#中如何使用枚举带开关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚如何结合使用开关,具有枚举。你能告诉我,我做错了什么,以及如何解决它?我必须用枚举做一个基本的计算器。

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?

推荐答案

您无需将其转换

switch(op)
{
     case Operator.PLUS:
     {

     }
}

顺便说一句,用括号

这篇关于C#中如何使用枚举带开关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆