簡體   English   中英

C#枚舉返回錯誤的int值

[英]C# Enums returning wrong int value

public enum Question
{
    A= 02,
    B= 13,
    C= 04,
    D= 15,
    E= 06,
}

但是當我使用

int something = (int)Question.A;

我得到2而不是02。如何獲得02?

整數不是字符串。 聽起來您想格式化一個至少包含兩位數字的字符串,可以使用以下方法進行處理:

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

區分值的文本表示形式和實際存儲在值中的信息非常重要。

例如,考慮:

int base10 = 255;
int base16 = 0xff;

這兩個變量具有相同的值。 它們使用不同形式的數字文字進行了初始化,但是它們具有相同的值。 兩者都可以設置為十進制,十六進制,二進制格式 ,無論您要使用什么格式 -但這些值本身無法區分。

022的字符串表示形式,帶有一個前置零。 如果需要在某個地方輸出該值,請嘗試使用自定義字符串格式:

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

or

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

有關此格式字符串的更多詳細信息,請參見MSDN ““ 0”自定義說明

整數是數字-就像貨幣一樣,$ 1等於$ 1.00和$ 000001。 如果要以某種方式顯示數字,可以使用:

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

將數字轉換為包含“ 02”的字符串。

2與02以及002和0002等完全相同。

檢查這篇文章: 通過C#在C#中使用字符串值進行枚舉 ,可以滿足輕松實現字符串的需求

您也可以嘗試此選項

 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();

02(索引)存儲為整數,因此您無法將其作為02!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM