How can I create an enum using numbers?

前端 未结 7 1395
野趣味
野趣味 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:53

    This isn't how enums work. An enumeration allow you to name a specific value so that you can refer to it in your code more sensibly.

    If you want to limit the domain of valid numeric, enums may not be the right choice. An alternative, is to just create a collection of valid values that can be used as gains:

    private int[] ValidGainValues = new []{ 1, 2, 4, 8};
    

    If you want to make this more typesafe, you could even create a custom type with a private constructor, define all of the valid values as static, public instances, and then expose them that way. But you're still going to have to give each valid value a name - since in C# member/variable names cannot begin with a number (although they can contain them).

    Now if what you really want, is to assign specific values to entries in a GainValues enumeration, that you CAN do:

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

提交回复
热议问题