Enum.ToString return wrong value?

后端 未结 2 563
借酒劲吻你
借酒劲吻你 2020-12-19 13:01

I have a simple enum:

public enum MyEnum
{
    [Description(\"Zero\")]
    Zero,
    [Description(\"A positive number\")]
    Positive,
    [Description(\"An         


        
相关标签:
2条回答
  • 2020-12-19 13:38

    It happens because you have set reserved to 2. If you want to set values for your enums, you should do all or none.

    0 讨论(0)
  • 2020-12-19 13:49

    when defining an enum the first value start with 0 and it going up from there unless you define other wise, so in your case it's:

    public enum MyEnum
            {
                [Description("Zero")]
                Zero, //0
                [Description("A positive number")]
                Positive, //1
                [Description("Any integer")]
                AnyInteger, //2
                [Description("A negative number")]
                Negative, //3
                [Description("Reserved number")]
                Reserved = 2 // it's 2 again
               }
    

    you can define the same value twice (or more) in a enum. the ToString find a name with the same value:

    MyEnum temp=MyEnum.AnyInteger; //temp = 2
    
    string en=temp.ToString(); // return the name of the first name with value 2.
    

    if you insist that "Reserved" should have the value 2, put him in the right place of order. otherwise remove the =2

    0 讨论(0)
提交回复
热议问题