繁体   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