variable that can't be modified

后端 未结 9 1805
我寻月下人不归
我寻月下人不归 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 02:53

    You can roll your own using a custom setter (but don't use Object unless you have to, choose the correct class):

    private Object myObj = null;
    private Boolean myObjSet = false;
    
    public Object MyObj
    {
        get { return this.myObj; }
        set 
        { 
            if (this.myObjSet) throw new InvalidOperationException("This value is read only");
            this.myObj = value;
            this.myObjSet = true;
        }
    }
    

    EDIT:

    This doesn't stop the private field being changed by the class internals.

提交回复
热议问题