How can I create an enum using numbers?

前端 未结 7 1409
野趣味
野趣味 2021-01-11 11:11

Is it possible to make an enum using just numbers in C#? In my program I have a variable, Gain, that can only be set to 1, 2, 4, and 8. I am using a propertygrid control to

7条回答
  •  醉话见心
    2021-01-11 11:51

    use explicit value assignment in the enum:

    private enum GainValues 
    {
       One = 1, 
       Two = 2, 
       Four = 4, 
       Eight = 8
    }
    

    Then to enumerate through these values do as follows:

    GainValues currentVal;
    
    foreach(currentVal in Enum.GetValues(typeof(GainValues))
    {
       // add to combo box (or whatever) here
    }
    

    Then you can cast to/from ints as necessary:

    int valueFromDB = 4;
    
    GainValues enumVal = (GainValues) valueFromDB;
    
    // enumVal should be 'Four' now
    

提交回复
热议问题