问题:
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