Automated property with getter only, can be set, why?

前端 未结 6 2094
暗喜
暗喜 2020-12-02 16:27

I created an automated property:

public int Foo { get; } 

This is getter only. But when I build a constructor, I can change the value:

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 16:50

    A variable declared readonly can be written within a constructor, but in languages which honor the attribute, cannot be modified after the constructor returns. That qualifier was provided as a language feature because it is often necessary for fields whose values will vary based upon constructor parameters (meaning they can't be initialized before the constructor starts) but won't have to change after constructors return, but it was only usable for variables exposed as fields. The semantics of readonly-qualified fields would in many cases have been perfect for public members except that it's often better for classes to expose members--even immutable ones--as properties rather than fields.

    Just as read-write auto-properties exist to allow classes to expose mutable properties as easily as ordinary fields, read-only auto-properties exist to allow classes to expose immutable properties as easily as readonly-qualified fields. Just as readonly-qualified fields can be written in a constructor, so too with get-only properties.

提交回复
热议问题