c# - 有没有理由拥有没有 setter/getter 的属性(property)?

标签 c# properties

我的经理问我使用带有 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/

相关文章:

java - 为 kafka 消费者使用多个反序列化器

c# - 存储多个值,其中一些值需要在运行时更改,以便通过单个键引用

vb.net - 与使用带有 getter 和 setter 的 Private 字段相比,VB.NET 中的 Property 关键字有哪些优势?

C#属性,这两个实现有什么区别?

c# - 动态创建 Hierarchical ContextMenu MVVM

express - 使用 Node 和 Express 向请求添加属性

c# - 如何在 asp.net c# 中为 BasicDatePicker 分配属性?

c# - 从 Sitecore 的 Lucene 搜索索引中选择性地排除项目 - 在使用 IndexViewer 重建时有效,但在使用 Sitecore 的内置工具时无效

c# - LINQ 上的简单查询

c# - WebSphere MQ .NET API