10

enum の値をケースバイケースで処理する場合、switch ステートメントと辞書のどちらを使用するのがよいでしょうか?

辞書の方が早いと思います。スペースに関しては、メモリ内でいくらか占有しますが、case ステートメントも、プログラム自体に必要なメモリ内でいくらかのメモリを占有します。要するに、辞書を使用する方が常に良いと思います。

比較のために、2 つの実装を並べて示します。

これらの列挙型を考えると:

enum FruitType
{
    Other,
    Apple,
    Banana,
    Mango,
    Orange
}
enum SpanishFruitType
{
    Otra,
    Manzana, // Apple
    Naranja, // Orange
    Platano, // Banana
    Pitaya // Dragon fruit, only grown in Mexico and South American countries, lets say
    // let's say they don't have mangos, because I don't remember the word for it.
}

これは、switch ステートメントを使用して行う方法です。

private static SpanishFruitType GetSpanishEquivalent(FruitType typeOfFruit)
{
    switch(typeOfFruit)
    {
        case FruitType.Apple:
            return SpanishFruitType.Manzana;
        case FruitType.Banana:
            return SpanishFruitType.Platano;
        case FruitType.Orange:
            return SpanishFruitType.Naranja;
        case FruitType.Mango:
        case FruitType.Other:
            return SpanishFruitType.Otra;
        default:
            throw new Exception("what kind of fruit is " + typeOfFruit + "?!");
    }
}

そして、辞書を使ってそれを行う方法は次のとおりです。

private static Dictionary<FruitType, SpanishFruitType> EnglishToSpanishFruit = new Dictionary<FruitType, SpanishFruitType>()
{
    {FruitType.Apple, SpanishFruitType.Manzana}
    ,{FruitType.Banana, SpanishFruitType.Platano}
    ,{FruitType.Mango, SpanishFruitType.Otra}
    ,{FruitType.Orange, SpanishFruitType.Naranja}
    ,{FruitType.Other, SpanishFruitType.Otra}
};
private static SpanishFruitType GetSpanishEquivalentWithDictionary(FruitType typeOfFruit)
{
    return EnglishToSpanishFruit[typeOfFruit]; // throws exception if it's not in the dictionary, which is fine.
}

辞書の速度が向上するだけでなく、コード内の不要な文字列が少なくなります。これは常に辞書を使用する方が良いですか?3番目のより良い方法はありますか?

前もって感謝します。

4

4 に答える 4

3

翻訳は 1 対 1 または 1 対 1 でないため、各単語に ID を割り当てませんか。次に、ある列挙型から別の列挙型にキャストします

したがって、列挙型を次のように定義します

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
}

次に、変換方法を次のように定義します

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;
    }
}
于 2013-07-12T00:56:47.877 に答える