簡體   English   中英

我可以在案例中使用ENUM代替帶有Enums的switch語句嗎?

[英]Can I use an ENUM instead of a switch statement with Enums in the CASE?

我在應用程序中使用了ENUM和擴展名,如下所示:

public enum CO
{
    Random = 0,
    FirstToLast = 1,
    LastToFirst = 2,
}

public static partial class Extensions
{
    public static string Text(this CO cardOrder)
    {
        switch (cardOrder)
        {
            case CO.Random: return "Random";
            case CO.FirstToLast: return "1, 2, 3";
            case CO.LastToFirst: return "3, 2, 1";
        }
        return "";
    }
}

在代碼中,我設置了switch語句來決定更新數據庫:

switch (segControlCardOrder.SelectedValue)
{
   case "Random":
         App.DB.UpdateIntSetting(SET.Co, (int)CO.Random);
         break;
   case "1, 2, 3":
         App.DB.UpdateIntSetting(SET.Co, (int)CO.FirstToLast);
         break;
   case "3, 2, 1":
         App.DB.UpdateIntSetting(SET.Co, (int)CO.LastToFirst);
         break;
}

有沒有一種方法可以避免使用switch語句,而僅基於ENUM的值調用UpdateIntSettings?

您還可以添加另一種擴展方法(從字符串到枚舉)。 然后,您可以在語句中使用該方法:

public static CO CardOrder(this string cardOrder)
{
    switch (cardOrder)
    {
        case "Radom": return CO.Random;
        case "1, 2, 3": return CO.FirstToLast;
        case "3, 2, 1":  return CO.LastToFirst;
    }
    throw new ArgumentException(string.Format($"{cardOrder} is not a CO representation"));
}

使用簡單:

App.DB.UpdateIntSetting(SET.Co, (int)segControlCardOrder.SelectedValue.CardOrder());

您可以將Dictionary<string, CO>初始化為類的私有或靜態成員:

dict.Add("Random", CO.Random);
dict.Add("1, 2, 3", CO.FirstToLast);
dict.Add("3, 2, 1", CO.LastToFirst);

最后做:

App.DB.UpdateIntSetting(Set.CO, (int)dict[segControlCardOrder.SelectedValue]);

是的,但是效率較低。 您可以使用值的字典,例如:

var dict = new Dictionary<string, CO> { ["Random"] = CO.Random, ["1, 2, 3"] = CO.FirstToLast, ["3, 2, 1"] = CO.LastToFirst };
App.DB.UpdateIntSetting(SET.Co, (int)dict[segControlCardOrder.SelectedValue]);

或者只是將值設置為在變量中使用,然后將其傳遞給方法。 我更喜歡最后一種方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM