在自动属性中替代私有设置
本文关键字:设置 属性 | 更新日期: 2023-09-27 17:51:22
如果你不应该为自动属性使用私有setter(坏习惯),那么我怎么能从类内部私下设置它,并且仍然只向公众公开它?(假设我想在构造函数级别设置它,但仍然允许它通过get成为公共)?
示例类:
public class Car
{
//set the property via constructor
public SomeClass(LicensePlate license)
{
License = license
}
public LicensePlate License{get; private set;} // bad practice
}
您将该属性转换为具有后备字段且没有setter的属性。
public class Car
{
LicensePlate _license;
public Car(LicensePlate license)
{
_license = license;
}
public LicensePlate License
{
get { return _license; }
}
}