variable that can't be modified

后端 未结 9 2005
我寻月下人不归
我寻月下人不归 2021-01-04 02:14

Does C# allow a variable that can\'t be modified? It\'s like a const, but instead of having to assign it a value at declaration, the variable does not have any

9条回答
  •  梦谈多话
    2021-01-04 03:00

    If you want to assign the variable at runtime after the object containing it has been constructed you could use a custom property with a setter method that can only be modified once. ie.

    private myVariable = null;
    public object MyVariable
    {
       get { return myVariable; }
       set { if(myVariable == null ) myVariable = value;
    }
    

提交回复
热议问题