Shorten long switch case

后端 未结 2 1786
佛祖请我去吃肉
佛祖请我去吃肉 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:34

    Maybe this would be too much, but you can use enums and classes/structs plus a dictionary (as ggorlen suggested)

    Why enums? to avoid using hardcoded numbers; less error-prone and will improve readability;

    private enum CropType
    {
        Undefined = 0,
        Cabbages,
        Carrots,
        Eggplant,
        Melon,
        Mushroom,
        Potatoes,
        Pumpkin,
        Strawberries,
        Truffle,
        Wheat
    }
    
    private struct Crop
    {
        public CropType Type { get; private set; }
        public float GrowthFactor { get; private set; }
        public float HarvestFactor { get; private set; }
    
        public Crop(CropType type, float growthFactor, float harvestFactor) 
        {
            this.Type = type;
            this.GrowthFactor = growthFactor;
            this.HarvestFactor = harvestFactor;
        }
    }
    

    private Dictionary crops;
    private Dictionary Crops 
    {
        get 
        {
            if (crops == null) 
            {
                crops = new Dictionary() 
                {
                    { CropType.Cabbages, new Crop(CropType.Cabbages, 90, 1) },
                    { CropType.Carrots, new Crop(CropType.Carrots, 80, 5) }
                    // here you can add the rest of your products...
                };
            }
            return crops;
        }
    }
    
    public Crop GetCrop(CropType crop) 
    {
        if (!Crops.ContainsKey(type)) 
        {
            Debug.LogWarningFormat("GetCrop; CropType [{0}] not present in dictionary ", type);
            return null;
        }
    
        return Crops[type];
    }
    

    Here is where (finally) you will retrieve the values that you want.

    public float GetGrowthFactor(CropType type) 
    {
        var crop = GetCrop(type);
        return crop == null ? default(float) : crop.GrowthFactor;
    }
    
    public float GetHarvestFactor(CropType type) 
    {
        var crop = GetCrop(type);
        return crop == null ? default(float) : crop.HarvestFactor;
    }
    

    So you will ask for values in this way;

    private void Example()
    {
        var carrotsGrowth = GetGrowthFactor(CropType.Carrots);
    }
    

提交回复
热议问题