我的经理问我使用带有 setter 而没有 getter 的属性是否是好的做法。
public class PropertyWrapper
{
private MyClass _field;
public MyClass Property
{
set { _field = value; }
}
public string FirstProperty
{
get { return _field.FirstProperty; }
}
public string SecondProperty
{
get { return _field.SecondProperty; }
}
}
他将使用其他属性来公开私有(private)字段中的属性,由该 setter 设置。
我的建议是只使用私有(private)字段并将其设置在构造函数中,在这种情况下效果很好。如果我需要先有一个构造对象(甚至可能使用多态性),我仍然更喜欢 Load
方法,而不是无 getter 属性。
但我很感兴趣。我们都非常关注最佳实践,并努力确保我们的代码标准化。有没有人有任何关于 getter-less 属性的官方文章?或者更好 - 在 .NET Framework 本身中使用这种用法的示例?
最佳答案
官方文章: Design Guidelines for Developing Class Libraries -> Member Design Guidelines -> Property Design
Do not provide set-only properties.
If the property getter cannot be provided, use a method to implement the functionality instead. The method name should begin with Set followed by what would have been the property name. For example, AppDomain has a method called SetCachePath instead of having a set-only property called CachePath.
关于c# - 有没有理由拥有没有 setter/getter 的属性(property)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9535747/