How to declare a class instance as a constant in C#?

前端 未结 7 1041
逝去的感伤
逝去的感伤 2020-12-16 09:46

I need to implement this:

static class MyStaticClass
{
    public const TimeSpan theTime = new TimeSpan(13, 0, 0);
    public static bool IsTooLate(DateTime          


        
7条回答
  •  独厮守ぢ
    2020-12-16 10:34

    Constants have to be compile time constant, and the compiler can't evaluate your constructor at compile time. Use readonly and a static constructor.

    static class MyStaticClass
    {
      static MyStaticClass()
      {
         theTime = new TimeSpan(13, 0, 0);
      }
    
      public static readonly TimeSpan theTime;
      public static bool IsTooLate(DateTime dt)
      {
        return dt.TimeOfDay >= theTime;
      }
    }
    

    In general I prefer to initialise in the constructor rather than by direct assignment as you have control over the order of initialisation.

提交回复
热议问题