How to define an enum with string value?

后端 未结 18 1391
一生所求
一生所求 2020-12-12 14:53

I am trying to define an Enum and add valid common separators which used in CSV or similar files. Then I am going to bind it to a ComboBox as a dat

18条回答
  •  借酒劲吻你
    2020-12-12 15:07

    A class that emulates enum behaviour but using string instead of int can be created as follows...

    public class GrainType
    {
        private string _typeKeyWord;
    
        private GrainType(string typeKeyWord)
        {
            _typeKeyWord = typeKeyWord;
        }
    
        public override string ToString()
        {
            return _typeKeyWord;
        }
    
        public static GrainType Wheat = new GrainType("GT_WHEAT");
        public static GrainType Corn = new GrainType("GT_CORN");
        public static GrainType Rice = new GrainType("GT_RICE");
        public static GrainType Barley = new GrainType("GT_BARLEY");
    
    }
    

    Usage...

    GrainType myGrain = GrainType.Wheat;
    
    PrintGrainKeyword(myGrain);
    

    then...

    public void PrintGrainKeyword(GrainType grain) 
    {
        Console.Writeline("My Grain code is " + grain.ToString());   // Displays "My Grain code is GT_WHEAT"
    }
    

提交回复
热议问题