是否有任何理由在 C# 中使用私有属性? [英] Are there any reasons to use private properties in C#?
问题描述
我刚刚意识到 C# 属性构造 也可以与 private 访问修饰符一起使用:
I just realized that the C# property construct can also be used with a private access modifier:
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;
而且我无法想象什么时候我需要能够在内部get但不能set或set 但不是 get 私有字段:
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; }
或
private string Password { set; }
但也许有嵌套/继承类的用例,或者get/set可能包含逻辑而不是仅仅返回属性的值,尽管我倾向于保持属性严格简单并让显式方法执行任何逻辑,例如GetEncodedPassword()
.
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, e.g. GetEncodedPassword()
.
是否有人出于任何原因在 C# 中使用私有属性,或者它只是技术上可能但很少在实际代码中使用的结构之一?
很好的答案,通读它们我挑选了这些用于私有财产的用途:
Nice answers, reading through them I culled these uses for private properties:
- 当需要延迟加载私有字段时
- 当私有字段需要额外的逻辑或者是计算值时
- 因为私有字段很难调试
- 为了向自己出示合同"
- 在内部转换/简化公开的属性作为序列化的一部分
- 包装要在类中使用的全局变量
推荐答案
如果我需要缓存一个值并想要延迟加载它,我会使用它们.
I use them if I need to cache a value and want to lazy load it.
private string _password;
private string Password
{
get
{
if (_password == null)
{
_password = CallExpensiveOperation();
}
return _password;
}
}
这篇关于是否有任何理由在 C# 中使用私有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!