是否有任何理由在 C# 中使用私有屬性? - Are there any reasons to use private properties in C#?

問題:

I just realized that the C# property construct can also be used with a private access modifier:我剛剛意識到 C#屬性構造也可以與私有訪問修飾符一起使用:

private string Password { get; set; }

Although this is technically interesting, I can't imagine when I would use it since a private field involves even less ceremony :雖然這在技術上很有趣,但我無法想象我什麼時候會使用它,因爲私人領域涉及的儀式更少

private string _password;

and I can't imagine when I would ever need to be able to internally get but not set or set but not get a private field:我無法想象什麼時候我需要能夠在內部獲取但不能設置設置但不能獲取私有字段:

private string Password { get; }

or或者

private string Password { set; }

but perhaps there is a use case with nested / inherited classes or perhaps where a get/set might contain logic instead of just giving back the value of the property, although I would tend to keep properties strictly simple and let explicit methods do any logic, eg GetEncodedPassword() .但也許有嵌套/繼承類的用例,或者 get/set 可能包含邏輯而不是僅僅返回屬性的值,儘管我傾向於保持屬性嚴格簡單並讓顯式方法執行任何邏輯,例如GetEncodedPassword()

Does anyone use private properties in C# for any reason or is it just one of those technically-possible-yet-rarely-used-in-actual-code constructs?有沒有人出於任何原因在 C# 中使用私有屬性,或者它只是那些技術上可能但很少在實際代碼中使用的構造之一?

Addendum附錄

Nice answers, reading through them I culled these uses for private properties:很好的答案,通讀它們我挑選了這些用於私有財產的用途:

  • when private fields need to be lazily loaded當需要延遲加載私有字段時
  • when private fields need extra logic or are calculated values當私有字段需要額外的邏輯或者是計算值時
  • since private fields can be difficult to debug因爲私有字段可能難以調試
  • in order to "present a contract to yourself"爲了“向自己出示合同”
  • to internally convert/simplify an exposed property as part of serialization在內部轉換/簡化公開的屬性作爲序列化的一部分
  • wrapping global variables to be used inside your class包裝要在類中使用的全局變量

解決方案:

參考一: https://en.stackoom.com/question/Dt86
參考二: https://stackoom.com/question/Dt86
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章