Are protected members/fields really that bad?

前端 未结 6 1590
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 02:33

Now if you read the naming conventions in the MSDN for C# you will notice that it states that properties are always preferred over public and protected fields. I have even

6条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 03:12

    Public and/or protected fields are bad because they can be manipulated from outside the declaring class without validation; thus they can be said to break the encapsulation principle of object oriented programming.

    When you lose encapsulation, you lose the contract of the declaring class; you cannot guarantee that the class behaves as intended or expected.

    Using a property or a method to access the field enables you to maintain encapsulation, and fulfill the contract of the declaring class.

提交回复
热议问题