Set properties of a class only through constructor

前端 未结 5 1985
野趣味
野趣味 2021-01-01 11:39

I am trying to make the properties of class which can only be set through the constructor of the same class.

5条回答
  •  生来不讨喜
    2021-01-01 11:55

    Make the properties have readonly backing fields:

    public class Thing
    {
       private readonly string _value;
    
       public Thing(string value)
       {
          _value = value;
       }
    
       public string Value { get { return _value; } }
    }
    

提交回复
热议问题