C#中的案例/开关语句

dan*_*yrd 1 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";

            }
Run Code Online (Sandbox Code Playgroud)

我开始将VB转换为C#,并意识到为了拥有多个case语句,你必须声明它们.你可以看到我有11到30而且不想拥有所有这些线条.

Glo*_*oot 13

你不能在VB中使用C#中的比较.但是,您可以使用直通案例,如下所示:

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

case 3:
case 4:
  ShippingCost = "4.86";
  break;
Run Code Online (Sandbox Code Playgroud)

请注意,非空的情况下需要或者是throw,return或者break声明.另请注意,您只能查看空案例.

编辑:

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

if(Weight<=2) {
  ShippingCost = "3.69";
}
else if(Weight <= 4) {
  ShippingCost = "4.86";
}
... etc
Run Code Online (Sandbox Code Playgroud)

  • 为什么尝试使用C#的'switch'来复制VB的'Select Case'?VB的'Select Case'是一个比'switch'更通用的工具 - if/else是C#,相当于VB'Select Case'的范围. (2认同)

Dom*_*see 6

在C#中有直接的等价物,但是,您可以使用直通,因此您不必重复执行:

switch (Weight)
{
    case 0:
    case 1:
    case 2:
       ShippingCost = "3.69";
       break;
       ...
Run Code Online (Sandbox Code Playgroud)

如果语句可能在这种情况下更适合你:

if(Weight >= 0 && Weight <= 2){
    ShippingCost = "3.69";
} else if(Weight >= 3 && Weight <= 4){
    ShippingCost = "4.86";
}
...
Run Code Online (Sandbox Code Playgroud)


Sur*_*yan 5

尝试这样:此解决方案无需&&在您的else if语句中写入

if(Weight >= 11 && Weight <= 30)
{
   ShippingCost = "15.72";
}
else if(Weight >= 9)
{
   ShippingCost = "6.28";
}
else if(Weight >= 7)
{
   ShippingCost = "5.98";
}
else if(Weight >= 5)
{
   ShippingCost = "5.63";
}
else if(Weight >= 3)
{
   ShippingCost = "4.86";
}
else if(Weight >= 0)
{
   ShippingCost = "3.69";
}
Run Code Online (Sandbox Code Playgroud)


Kla*_*sen 5

你也可以把它写成Linq one liner:

var ShippingCost = (new[] { new { w = 2, p = "3,69" }, 
                            new { w = 4, p = "4.86" }, 
                            new { w = 6, p = "5.63" }, 
                            new { w = 8, p = "5.98" }, 
                            new { w = 10, p = "6.28" }, 
                            new { w = 30, p = "15.72" }})
             .First(x => Weight <= x.w).p;
Run Code Online (Sandbox Code Playgroud)

正如其他人已经说过的那样,您希望确保重量超过30的物品的运输也能正确处理.