C# protected property or field

后端 未结 5 1352
离开以前
离开以前 2021-01-01 13:47

Do you think it\'s better to always make protected class members an auto-implemented protected property to keep isolation or make it protected field is enough?



        
5条回答
  •  别那么骄傲
    2021-01-01 14:03

    The suggested practice is to make it a property. The signature changes depending on whether it's a field or a property, which can cause problems if you're crossing assemblies. If you make it a property to begin with, you'll never have this problem. (often later you want to add logic when the property is read or written.)

    In C#, auto-implementing the property is so easy, there's no reason not to do it.

    Also, it makes things more clear. If it is really meant to be used by the outside world as part of the functioning of the object, make it a property. Otherwise, a future programmer might wonder if you made a field protected instead of private by accident.

提交回复
热议问题