Readonly field that could be assigned a value outside constructor

后端 未结 7 1970
清酒与你
清酒与你 2021-01-22 16:19

Is there a way to have a private readonly field in a class that could be assigned a value anywhere in the class, but only once??

That is, I am looking for a private read

7条回答
  •  渐次进展
    2021-01-22 17:02

    You can use a private property that checks to see if it was assigned to and only assign a value if it hasn't been.

    int? _writeOnceField;
    
    private int? WriteOnce
    {
       set
       {
          if (!_writeOnceFiled.HasValue)
          {
            writeOnceFiled = value;
          }
          else
          {
            // Throw exception
          }
       }
    }
    

提交回复
热议问题