enum case handling - better to use a switch or a dictionary?

前端 未结 4 2043
逝去的感伤
逝去的感伤 2021-02-20 16:20

When handling the values of an enum on a case by case basis, is it better to use a switch statement or a dictionary?

I would think that the dictionary would be faster.

4条回答
  •  南笙
    南笙 (楼主)
    2021-02-20 16:43

    Since the translations are one-to-one or one-to-none, why not assign IDs to each word. Then cast from one enum to another

    So define your enums as

    enum FruitType
    {
        Other = 0,
        Apple = 1,
        Banana = 2,
        Mango = 3,
        Orange = 4
    }
    enum SpanishFruitType
    {
        Otra = 0,
        Manzana = 1, // Apple
        Platano = 2, // Banana
        Naranja = 4, // Orange
    }
    

    Then define your conversion method as

    private static SpanishFruitType GetSpanishEquivalent(FruitType typeOfFruit)
    {
        //'translate' with the word's ID. 
        //If there is no translation, the enum would be undefined
        SpanishFruitType translation = (SpanishFruitType)(int)typeOfFruit;
    
        //Check if the translation is defined
        if (Enum.IsDefined(typeof(SpanishFruitType), translation))
        {
            return translation;
        }
        else
        {
            return SpanishFruitType.Otra;
        }
    }
    

提交回复
热议问题