enum.ToString返回错误的值? [英] enum.ToString return wrong value?

查看:178
本文介绍了enum.ToString返回错误的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的枚举:

public enum MyEnum
        {
            [Description("Zero")]
            Zero,
            [Description("A positive number")]
            Positive,
            [Description("Any integer")]
            AnyInteger,
            [Description("A negative number")]
            Negative,
            [Description("Reserved number")]
            Reserved =2
           }

但是,运行以下代码:


MyEnum temp = MyEnum.AnyInteger;

MyEnum temp=MyEnum.AnyInteger;

string en = temp.ToString();

string en=temp.ToString();

将en字符串设置为Reserved。

sets the en string to Reserved.

为什么会这样?

有没有其他方法可以将字符串设置为使用的枚举字符串(在这种情况下为AnyInteger)?

Is there is some other way to set the string to the used enum string (in this case AnyInteger)?

推荐答案

当定义枚举时,第一个值以 0 开始,并且从那里开始,除非你定义其他明智的,所以在你的案例是:

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
           }

您可以在枚举中定义相同的值两次(或更多)。 ToString 找到一个具有相同值的名称:

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.

如果您坚持保留有价值2,把他放在正确的地方。否则删除 = 2

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

这篇关于enum.ToString返回错误的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆