将 if else 语句转换为 Switch 语句

问题描述 投票:0回答:1

我正在应对编写 C# 代码的挑战,该代码采用 if else 语句并将其转换为具有所有相同结果的 Select 语句。这是 if else 代码;

// SKU = Stock Keeping Unit. 
// SKU value format: <product #>-<2-letter color code>-<size code>
string sku = "01-MN-L";

string[] product = sku.Split('-');

string type = "";
string color = "";
string size = "";

if (product[0] == "01")
{
    type = "Sweat shirt";
} else if (product[0] == "02")
{
    type = "T-Shirt";
} else if (product[0] == "03")
{
    type = "Sweat pants";
}
else
{
    type = "Other";
}

if (product[1] == "BL")
{
    color = "Black";
} else if (product[1] == "MN")
{
    color = "Maroon";
} else
{
    color = "White";
}

if (product[2] == "S")
{
    size = "Small";
} else if (product[2] == "M")
{
    size = "Medium";
} else if (product[2] == "L")
{
    size = "Large";
} else
{
    size = "One Size Fits All";
}

Console.WriteLine($"Product: {size} {color} {type}");

这是我对这个问题的尝试,如果有例外,我无法处理其他问题 代码的一部分需要在 Switch 语句中使用多个 default: 语句。

using System.Drawing;
string color = "";
string type = "";
string size = "";
string sku = "02-BK-R";

string[] product = sku.Split('-');
int skuPart = product.Length;

foreach (string productPart in product)
{
    switch (productPart)
    {
        case "01":
            type = "Sweat Shirt";
            break;
        case "02":
            type = "T-Shirt ";
            break;
        case "03":
            type = "Sweat Pants";
            break;       
        case "MN":
            color = "Maroon";
            break;
        case "BK":
            color = "Black";
            break;

        case "S":
            size = "Small";
            break;
        case "M":
            size = "Medium";
            break;
        case "L":
            size = "Large";
            break;
        default:           
            break;
    }
}

 Console.WriteLine($"Product: {size} {color} {type}");
c# switch-statement
1个回答
0
投票

在我看来,最好的解决方案是编写3个switch语句来设置类型、颜色和大小的值。这就是您编写代码的方式:

var sku = "01-MN-L";

var product = sku.Split('-');

var type = product[0] switch
{
    "01" => "Sweat shirt",
    "02" => "T-Shirt",
    "03" => "Sweat pants",
    _ => "Other"
};

var color = product[1] switch
{
    "BL" => "Black",
    "MN" => "Maroon",
    _ => "White"
};

var size = product[2] switch
{
    "S" => "Small",
    "M" => "Medium",
    "L" => "Large",
    _ => "One Size Fits All"
};

Console.WriteLine($"Product: {size} {color} {type}");

我希望这个解决方案可以帮助你。

© www.soinside.com 2019 - 2024. All rights reserved.