variable that can't be modified

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

    Sure. You can use readonly:

    I.e.: public readonly int z;

    This can only be modified from within the constructor.

    From MSDN:

    You can assign a value to a readonly field only in the following contexts:

    When the variable is initialized in the declaration, for example:

    • public readonly int y = 5;

    • For an instance field, in the instance constructors of the class that contains the field declaration, or for a static field, in the static constructor of the class that contains the field declaration. These are also the only contexts in which it is valid to pass a readonly field as an out or ref parameter.

    If however you are wanting to make a property that can only be altered within the class that created it, you can use the following:

    public string SetInClass
    {
       get;
       private set;
    }
    

    This allows changes to be made within the class, but the variable cannot be altered from outside the class.

提交回复
热议问题