Why we can't have “char” enum types

前端 未结 9 1010
不知归路
不知归路 2020-12-06 03:50

I want to know why we can\'t have \"char\" as underlying enum type. As we have byte,sbyte,int,uint,long,ulong,short,ushort as underlying enum type. Second what is the defau

9条回答
  •  猫巷女王i
    2020-12-06 04:45

    Technically, you can't do this. But, you can convert the enum to a byte and then convert that to char. This is useful if your goal is to have something like this (realizing this is impossible to do:

    public enum CharEnum
    {
        one = '1'
    }
    

    You can do this, however, by using ASCII byte values and then converting:

    public enum CharEnum
    {
        one = 49,
        two = 50
    }
    

    You can then convert to byte and to char to get the char value. It is not really pretty, but it will work, if getting a char is your ultimate goal. You can also use unicode and an int value, if you need chars outside of the ASCII range. :-)

提交回复
热议问题