Shorten long switch case

后端 未结 2 1824
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-28 17:08

So let me start by saying I am new to C#. I have a switch statement that currently has 10 different cases, however, I need to use it 3 different times (same 10 cases, different

2条回答
  •  醉酒成梦
    2021-01-28 17:33

    In terms of simplifying a switch statement, I think a Dictionary (if keys were not sequential integers), enumeration, or a List (for something like 1-10 as is the case here) is appropriate, creating a mapped relationship between numbers:

    int[] growth = {0, 60, 80, 90, 40, 120, 130, 50, 70, 40, 150};
    int cropType = 5; // for example
    Console.WriteLine(growth[cropType]); // 120
    

    Here's a dictionary example, which I think is more comprehensible for humans:

    Dictionary growth = new Dictionary()
    {
        {"Potatoes", 60}, 
        {"Strawberries", 80}, 
        {"Cabbages", 90}, 
        {"Carrots", 40}, 
        {"Melon", 120}, 
        {"Pumpkin", 130}, 
        {"Eggplant", 50}, 
        {"Mushroom", 70}, 
        {"Wheat", 70}, 
        {"Truffle", 150} 
    };
    
    Console.WriteLine(growth["Melon"]);
    

    However, having seen your second switch statement, it appears your unwieldy switches are symptoms of a larger design problem. You may consider adding a Crop class that has member fields for all of the properties you're manipulating, such as type and growth (and any other properties or functions that describe Crop-ness).

    In terms of Global, you may consider a second class that aggregates Crops, such as a Harvest class with a dictionary that keeps tracks of how much of each crop have been harvested.

    Long story short, these design questions can get quite fuzzy and opinion-based, but hopefully this offers some ideas for moving forward.

提交回复
热议问题