在C#中不能在开关中使用十进制范围吗? [英] Is using decimal ranges in a switch impossible in C#?

查看:70
本文介绍了在C#中不能在开关中使用十进制范围吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习C#,但是我已经陷入了非常基础的问题。

I'm just starting out learning C# and I've become stuck at something very basic.

对于我的第一个应用程序,我认为我会去很简单,所以我决定使用BMI计算器。

For my first "app" I thought I'd go for something simple, so I decided for a BMI calculator.

BMI被计算为十进制类型,我现在正尝试在switch语句中使用它,但显然是十进制不能在交换机中使用?

The BMI is calculated into a decimal type which I'm now trying to use in a switch statement, but aparently decimal can't be used in a switch?

C#解决方案是什么:

What would be the C# solution for this:

            decimal bmi = calculate_bmi(h, w);

            switch (bmi) {
                case < 18.5: 
                    bmi_description = "underweight.";
                    break;
                case > 25:
                    bmi_description = "overweight";
                case > 30:
                    bmi_description = "very overweight";
                case > 40:
                    bmi_description = "extreme overweight";
                    break;
            }


推荐答案

switch 语句仅支持整数类型(枚举未列出,但可与 switch 语句一起使用,因为它们由整数类型支持)(字符串也受Changeling指出支持-请参阅注释以供参考)和具有常数值的相等比较。因此,您必须使用一些 if 语句。

The switchstatement only supports integral types (enumerations are not listed but can be used with switch statements because they are backed by an integral type)(strings are also supported as pointed out by Changeling - see the comment for reference) and equality comparisons with constant values. Therefore you have to use some if statements.

if (bmi < 18.5M)
{
    bmi_description = "underweight.";
}
else if (bmi <= 25)
{
    // You missed the 'normal' case in your example.
}
else if (bmi <= 30)
{
    bmi_description = "overweight";
}
else if (bmi <= 40)
{
    bmi_description = "very overweight";
}
else
{
    bmi_description = "extreme overweight";
}

顺便说一下,您的switch语句有点怪异,因为您要从较少大于并使用不间断的落差。我认为应该只使用一种比较方式,以使代码更易于理解或对支票进行重新排序,并且不要使用掉线。

By the way your switch statement is a bit weired because you are switching from less than to greater than and using fall-through without breaks. I think one should use only one type of comparison to make the code easier to understand or reorder the checks and do not use fall-through.

if (bmi < 18.5M)
{
    bmi_description = "underweight.";
}
else if (bmi > 40)
{
    bmi_description = "extreme overweight";
}
else if (bmi > 30)
{
    bmi_description = "very overweight";
}
else if (bmi > 25)
{
    bmi_description = "overweight";
}
else
{
    // You missed the 'normal' case in your example.
}

这篇关于在C#中不能在开关中使用十进制范围吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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