有没有理由拥有一个没有 getter 的属性? [英] Is there any reason to have a property with no getter?

查看:47
本文介绍了有没有理由拥有一个没有 getter 的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的经理问我使用带有 setter 但没有 getter 的属性是否是一种好习惯.

My manager has asked me if it is good practice to use a property with a setter, but no 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; } 
    }
}

他将使用其他属性来公开此 setter 设置的私有字段中的属性.

He would be using other properties to expose properties from a private field, set by this setter.

我的建议是只使用私有字段并将其设置在构造函数中,这在这种情况下工作正常.如果我需要先构造一个对象(甚至可能使用多态),我仍然更喜欢 Load 方法,而不是无 getter 属性.

My suggestion was to just use a private field and set it in the constructor, which works fine in this scenario. If I needed to have a constructed object first (maybe even using polymorphism) I would still prefer a Load method, rather than a getter-less property.

但我很感兴趣.我们都非常关注最佳实践,并努力确保我们的代码是标准化的.有没有人有任何关于 getter-less 属性的官方文章?或者更好 - .NET Framework 本身中这种用法的示例?

But I'm interested. We're both very concerned by best-practices and try to make sure our code is standarised. Does anyone have any official articles about getter-less properties? Or better still - an example of this usage in the .NET Framework itself?

推荐答案

官方文章:开发类库的设计指南 ->成员设计指南 ->物业设计

Official article: Design Guidelines for Developing Class Libraries -> Member Design Guidelines -> Property Design

请勿提供仅限设置的属性.

如果无法提供属性getter,则使用方法实现而是功能.方法名称应以 Set 开头然后是属性名称.例如,AppDomain 有一个名为 SetCachePath 的方法,而不是有一个仅设置名为 CachePath 的属性.

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.

这篇关于有没有理由拥有一个没有 getter 的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆