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

前端 未结 7 1057
逝去的感伤
逝去的感伤 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-16 10:11

    You can use the readonly keyword:

    When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.

    Example (copied from the linked MSDN page):

    class Age
    {
        readonly int _year;
        Age(int year)
        {
            _year = year;
        }
        void ChangeYear()
        {
            //_year = 1967; // Compile error if uncommented.
        }
    }
    

提交回复
热议问题