2011-10-11 106 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 - 你是受歡迎的..... –