Why do I need a private field that is exposed via public property?

前端 未结 11 750
天涯浪人
天涯浪人 2020-12-11 11:41

I\'m comming from Java world mainly. So, C# properties do look nice.

I know that with C# 3.0 or above I can use Automatic Properties. I like it even more :).

11条回答
  •  渐次进展
    2020-12-11 11:52

    The bog-standard answer would be "encapsulating the implementation detail of how and where the age is stored".

    For retrieval purposes, a more realistic example might be that one day, you could potentially want to access the value in a way that means direct access isn't so good. For example, if it's a value that you might be caching elsewhere, or if it's a calculated value.

    In terms of encapsulating the setting process, it means you can embed some model-level validation into the setter; if someone tries to set a conceptually invalid value, you can throw an IllegalArgumentException and reject it.

    In these cases, the encapsulation means that all your existing code doesn't have to change because you had to wrap up the value in something.

提交回复
热议问题