How to define an enum with string value?

后端 未结 18 1419
一生所求
一生所求 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:16

    You can't - enum values have to be integral values. You can either use attributes to associate a string value with each enum value, or in this case if every separator is a single character you could just use the char value:

    enum Separator
    {
        Comma = ',',
        Tab = '\t',
        Space = ' '
    }
    

    (EDIT: Just to clarify, you can't make char the underlying type of the enum, but you can use char constants to assign the integral value corresponding to each enum value. The underlying type of the above enum is int.)

    Then an extension method if you need one:

    public string ToSeparatorString(this Separator separator)
    {
        // TODO: validation
        return ((char) separator).ToString();
    }
    

提交回复
热议问题