Encapsulation C# newbie

前端 未结 5 987
我在风中等你
我在风中等你 2021-01-02 22:54

New to C#, and I understand that encapsulation is just a way of \"protecting data\". But I am still unclear. I thought that the point of get and set accessors wer

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-02 23:05

    By using public string MyName { get; set; }, you leave an ability to change its logic later without the need to recompile/change other code that uses your property.

    For example, if you are making a library and v1 uses a field and v2 uses a property, applications that work with v1 will not work with v2 without recompilation (and, potentially, code changes if they are written in some .NET language that has different syntax for accessing fields).

    Another important difference is in serialization scenarios -- a lot of them do not support fields. Also any interface that requires a property can not be implemented without using one, but depending on interface it may not be required to do any additional checks/logic in it.

提交回复
热议问题