variable that can't be modified

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

    It is possible to mark a field readonly which will require you set it a value either at point of declaration or in the constructor and then will prevent it from being reassigned post construction.

    However, whilst the reference will be read-only, the object will not necessarily be so too. To prevent the object itself from being modified you will have to make the type immutable or else provide an wrapper class that only exposes the non-destructive methods and properties of the underlying type.

提交回复
热议问题