Readonly field that could be assigned a value outside constructor

后端 未结 7 1893
清酒与你
清酒与你 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:09

    You won't get compile time error, but you can accomplish what you're looking for with a property. In the setter, only set the value if an internal bool/flag is false. Once you set it the first time, set the flag to true. And if the setter is invoked again by another piece of code, you can throw an InvalidOperationException to let them know it has already been initialized

    private bool fieldAlreadySet = false;
    private string field;
    
    public string Field
    {
       get {return field;}
       set
       {
           if (fieldAlreadySet) throw new InvalidOperationException("field already set");
           this.field = value;
           fieldAlreadySet = true;
       }
    }
    
    0 讨论(0)
提交回复
热议问题