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

前端 未结 7 1043
逝去的感伤
逝去的感伤 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:37

    From this link:

    Constants must be a value type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool), an enumeration, a string literal, or a reference to null.

    If you want to create an object, it must be done so as static readonly:

    static class MyStaticClass
    {
      public static readonly TimeSpan theTime = new TimeSpan(13, 0, 0);
      public static bool IsTooLate(DateTime dt)
      {
        return dt.TimeOfDay >= theTime;
      }
    }
    
    0 讨论(0)
提交回复
热议问题