Why should I avoid using Properties in C#?

后端 未结 14 527
渐次进展
渐次进展 2020-12-22 18:05

In his excellent book, CLR Via C#, Jeffrey Richter said that he doesn\'t like properties, and recommends not to use them. He gave some reason, but I don\'t really understand

相关标签:
14条回答
  • 2020-12-22 18:41

    I can't help picking on the details of Jeffrey Richter's opinions:

    A property may be read-only or write-only; field access is always readable and writable.

    Wrong: Fields can marked read-only so only the object's constructor can write to them.

    A property method may throw an exception; field access never throws an exception.

    Wrong: The implementation of a class can change the access modifier of a field from public to private. Attempts to read private fields at runtime will always result in an exception.

    0 讨论(0)
  • 2020-12-22 18:42

    I don't see any reasons why you shouldn't use Properties in general.

    Automatic properties in C# 3+ only simplify syntax a bit (a la syntatic sugar).

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