c# - C# 中的 Case/Switch 语句

标签 c# vb.net

我想知道是否有一种方法可以声明很多 case 语句而不必全部编写。比如我的代码:

            switch (Weight)
            {
                case 0 to 2;
                    ShippingCost = "3.69";

                case 3 to 4;
                    ShippingCost = "4.86";

                case 5 to 6;
                    ShippingCost = "5.63";

                case 7 to 8;
                    ShippingCost = "5.98";

                case 9 to 10;
                    ShippingCost = "6.28";

                case 11 to 30;
                    ShippingCost = "15.72";

            }

我开始将 VB 转换为 C#,并意识到要拥有多个 case 语句,您必须声明它们。如您所见,我有 11 到 30 条线,但不想拥有所有这些线。

最佳答案

您不能像在 VB 中那样在 C# 中使用比较。但是,您可以使用 fall-through cases,如下所示:

case 0:
case 1:
case 2:
  ShippingCost = "3.69";
  break;

case 3:
case 4:
  ShippingCost = "4.86";
  break;

请注意,非空情况需要 throwreturnbreak 语句。另请注意,您只能在空情况下失败。

编辑:

为了完整性,正如其他人所指出的,在这种情况下使用一系列 if 语句可能更明智,如下所示:

if(Weight<=2) {
  ShippingCost = "3.69";
}
else if(Weight <= 4) {
  ShippingCost = "4.86";
}
... etc

关于c# - C# 中的 Case/Switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33782845/

相关文章:

c# - 为什么函数调用要花这么多时间?

c# - ASP.Net Core docker从服务容器访问服务容器抛出ssl证书错误

c# - 如何监控焦点变化?

mysql - 参数化查询显示 "Mixing named and unnamed parameters is not allowed."

VB.NET - 如何使用外部 .resources 文件中的图片?

c# - Visual Studio、Razor、BuildProviders 和 Intellisense

C# 虚方法覆盖返回类型和方法参数

c# - 带有 Interop.Word 的斜体内联字

sql - 计算 SQL 表中超过 1 行出现 2 个不同值的次数

asp.net - 在 VB.Net 中将字符串转换为 Guid