How to define an enum with string value?

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

    You can achieve it but will required bit of work.

    1. Define an attribute class which will contain the string value for enum.
    2. Define an extension method which will return back the value from the attribute. Eg..GetStringValue(this Enum value) will return attribute value.
    3. Then you can define the enum like this..
    public enum Test : int {
        [StringValue("a")]
        Foo = 1,
        [StringValue("b")]
        Something = 2        
    } 
    
    1. To get back the value from Attrinbute Test.Foo.GetStringValue();

    Refer : Enum With String Values In C#

提交回复
热议问题