开发者

Enum to formatted string

public enum WebWizDateFormat
{
    DDMMYY,
    MMDDYY,
    YYDDMM,
    YYMMDD
}

 

public class WebWizForumUser
{
    public WebWizDateFormat DateFormat { get; set; }

    public WebWizForumUser()
    {
        this.DateFormat = WebWizDateFormat.DDMMYY;
        HttpContext.Current.Response.Write(this.DateForm开发者_运维百科at);
    }
}

This works, but when I response.write it needs to come out in the format "dd/mm/yy", how can I do this?


The simple answer is don't use an enum for this. How about a static class?

public static class WebWizDateFormat
{
    public const string USFormat = "MM/DD/YY";
    public const string UKFormat = "DD/MM/YY";
}

// . . .
string dateFormat = WebWizDateFormat.USFormat;

(Just a sample, rename the fields to whatever makes sense for you.)


Easiest way would be to just use a Dictionary<WebWizDateFormat,string> that you populate with corresponding string represenations for your enum, i.e.

DateMapping[WebWizDateFormat.DDMMYY] = "dd/mm/yy";

then you can just do

HttpContext.Current.Response.Write(DateMapping[this.DateFormat]);


Your rules regarding this conversion are not clear. You could do something like that:

this.DateFormat.ToLower().Insert(4, "\\").Insert(2,"\\");

But I doubt, that is what you meant... ;-)
This could also be helpful to you: Enum ToString with user friendly strings


Preamble: I would advise against using an enum item name to represent data (you can get the string name of a given enum value and type). I would also advise using implicitly assigned enum values as subtle changes such as adding or removing an enum item may create subtle incompatible changes/bugs.

In this case I may just create a map from an enum-value to a string format, such as:

public enum WebWizDateFormat
{
    DDMMYY = 1,
    MMDDYY = 2,
    YYDDMM = 3,
    YYMMDD = 4,
    // but better, maybe, as this abstracts out the "localization"
    // it is not mutually exclusive with the above
    // however, .NET *already* supports various localized date formats
    // which the mapping below could be altered to take advantage
    ShortUS = 10, // means "mm/dd/yy",
    LongUK = ...,
}

public IDictionary<string,string> WebWizDateFormatMap = new Dictionary<string,string> {
    { WebWizDateFormat.DDMMYY, "dd/mm/yy" },
    // "localized" version, same as MMDDYY
    { WebWizDateFormat.ShortUS, "mm/dd/yy" },
    ... // define for -all-
};

// to use later
string format = WebWizDateFormatMap[WebWizDateFormat.ShortUS];

Happy coding

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜