开发者

using DateTime object inside enum

I have this enum:

public enum TimePeriod
{
    Day = DateTime.No开发者_StackOverflow社区w.AddDays(-1),
    Week = DateTime.Now.AddDays(-7),
    Month = DateTime.Now.AddMonths(-1),
    AllTime = DateTime.Now
}

but cant do

(DateTime)timePeriod

how can i get the date given an enum?


In C#, the default underlying type for an enum is int, and unfortunately is only support basic data types like int, short, uint and so on. Therefore, storing the DateTimes inside an enum is not possible in .NET.

You can of course make a static class with static properties that expose the DateTimes you need instead of making it like an enum like this:

public static class TimePeriod
{
  public static DateTime Day{ get{return DateTime.Now.AddDays(-1);}},
  public static DateTime Week{ get{return DateTime.Now.AddDays(-7);}},
  public static DateTime Month{ get{return DateTime.Now.AddMonths(-1);}},
  public static DateTime AllTime{ get{return DateTime.Now;}},
}

And use it like this:

myDateTime = TimePeriod.Month;


In addition to Oyvind's answer. Enums Values have to be constant values and not variables.


You should use a class, not an enum for this.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜