我在C#中的数字格式没有给我一个填充号码

时间:2013-02-08 13:17:11

标签: c#

我使用以下内容:

    public static SelectList GetOptions<T>(string value = null) where T : struct
    {
        var values = EnumUtilities.GetSpacedOptions<T>();
        var options = new SelectList(values, "Value", "Text", value);
        return options;
    }

    public static IEnumerable<SelectListItem> GetSpacedOptions<T>(bool zeroPad = false) where T : struct
    {
        var t = typeof(T);
        if (!t.IsEnum)
        {
            throw new ArgumentException("Not an enum type");
        }
        var numberFormat = zeroPad ? "D2" : "g";
        var options = Enum.GetValues(t).Cast<T>()
            .Select(x => new SelectListItem
            {
                Value = ((int) Enum.ToObject(t, x)).ToString(numberFormat),
                Text = Regex.Replace(x.ToString(), "([A-Z])", " $1").Trim()
            });
        return options;

我的枚举有价值观:

public enum DefaultStatus {
    Release = 0,
    Review = 1,
    InProgress = 2,
    Concept = 3,
    None = 99
};

根据我的理解,数字格式应该给出我的值“01”,“02”等,但它给了我“”1“,”2“,”3“..

有什么明显的东西我做错了吗?

1 个答案:

答案 0 :(得分:1)

您的GetSpacedOptions包含可选参数zeroPad,默认值为false

使用

var values = EnumUtilities.GetSpacedOptions<T>(true);

而不是

var values = EnumUtilities.GetSpacedOptions<T>();
相关问题