Private Set or Private member?

前端 未结 7 2201
旧时难觅i
旧时难觅i 2020-12-29 05:05

I was wondering what\'s considered the C# best practice, private/protected members with public getters, or public getters with private/protected setters?

            


        
相关标签:
7条回答
  • 2020-12-29 05:54

    In my opinion there is no best practice and very little (if any) difference in the resulting compiled code, it really just depends on your needs or own likes/dislikes. If you're following your group's naming standards and meeting requirements (e.g. don't need to propagate a change notification) then it shouldn't matter.

    An advantage of private fields is that you can define a default value in the same place as your declaration. In an auto-implemented property you'll have do define the default in the constructor if it's not null or the type's default value.

    However, I still like private setters. But we usually don't use auto-implemented properties since our setters usually have a richer functionality - e.g. property update notifications, logging, etc.

    0 讨论(0)
提交回复
热议问题