2011-10-11 108 views
1
public enum Question 
{ 
    A= 02, 
    B= 13, 
    C= 04, 
    D= 15, 
    E= 06, 
} 

但是当我使用C#枚举返回错误int值

int something = (int)Question.A; 

我得到2,而不是02.我怎样才能获得02?

+0

2是相同的02 – harold

+0

噢,如果你做一个2 == 02它将等于。 2和02,整体而言,是相同的。 – UrbanEsc

+0

你根本不能:它是一个整数,所以正确的结果是2!02是一个字符串,你不能用它作为枚举的结果 – Marco

回答

8

整数不是字符串。这听起来像你想至少有两个数字,你可以用做格式化字符串:

string text = value.ToString("00"); // For example; there are other ways 

它的值的文本表示区分是很重要的,而实际存储是信息值为

例如,请考虑:

int base10 = 255; 
int base16 = 0xff; 

这两个变量的值相同。它们使用不同形式的数字文字初始化,但它们的值相同。无论你想要什么,它们都可以是格式为的十进制,十六进制,二进制,但是这些值本身是无法区分的。

0

02(索引)存储为整数,所以你不能把它作为02!

1

整数是数字 - 就像金钱一样,$ 1等于$ 1.00和$ 000001。如果你想显示以某种方式一个数字,你可以使用:

string somethingReadyForDisplay = something.ToString("D2"); 

其数量转换为包含“02”的字符串。

2

02是前导零的2的字符串表示形式。如果您需要输出这个值的地方尽量使用自定义字符串格式:

String.Format("{0:00}", (int)Question.A) 

or 

((int)Question.A).ToString("00") 

有关详细信息有关此格式字符串请参阅MSDN上"The "0" Custom Specifier"

+0

thx,但我总是得到00 – senzacionale

+0

@senzacionale:对不起,我已经更新了答案。忘记添加第一个参数占位符 – sll

1

2是完全一样的02和002和技术等。

1

检查这个帖子:Enum With String Values In C#本可以满足您的需求轻松realated串

您也可以尝试这个选项

public enum Test : int { 
     [StringValue("02")] 
     Foo = 1, 
     [StringValue("14")] 
     Something = 2  
} 

新的自定义属性类,它的源代码如下:

/// <summary> 
/// This attribute is used to represent a string value 
/// for a value in an enum. 
/// </summary> 
public class StringValueAttribute : Attribute { 

    #region Properties 

    /// <summary> 
    /// Holds the stringvalue for a value in an enum. 
    /// </summary> 
    public string StringValue { get; protected set; } 

    #endregion 

    #region Constructor 

    /// <summary> 
    /// Constructor used to init a StringValue Attribute 
    /// </summary> 
    /// <param name="value"></param> 
    public StringValueAttribute(string value) { 
     this.StringValue = value; 
    } 

    #endregion 

} 

创造了一个新的扩展方法,我将用它来获得一个枚举值的字符串值:

/// <summary> 
    /// Will get the string value for a given enums value, this will 
    /// only work if you assign the StringValue attribute to 
    /// the items in your enum. 
    /// </summary> 
    /// <param name="value"></param> 
    /// <returns></returns> 
    public static string GetStringValue(this Enum value) { 
     // Get the type 
     Type type = value.GetType(); 

     // Get fieldinfo for this type 
     FieldInfo fieldInfo = type.GetField(value.ToString()); 

     // Get the stringvalue attributes 
     StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
      typeof(StringValueAttribute), false) as StringValueAttribute[]; 

     // Return the first if there was a match. 
     return attribs.Length > 0 ? attribs[0].StringValue : null; 
    } 

终于看完值通过

Test t = Test.Foo; 
string val = t.GetStringValue(); 

- or even - 

string val = Test.Foo.GetStringValue(); 
+0

thx林蛙。我发现原来的链接:http://www.codeproject.com/KB/cs/stringenum.aspx – senzacionale

+0

@senzacionale - 你是受欢迎的..... –