variable that can't be modified

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

    You can define a readonly variable that can only have it's value set in the objects constructor.

    Read about it here: http://msdn.microsoft.com/en-us/library/acdd6hb7%28v=VS.100%29.aspx

    0 讨论(0)
  • 2021-01-04 03:13

    You can declare a readonly field variable which can be set only in the constructor or directly through its declaration.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题