我刚刚意识到c#属性结构也可以与私有访问修饰符一起使用:

private string Password { get; set; }

虽然这在技术上很有趣,但我无法想象我什么时候会使用它,因为私人领域涉及的仪式甚至更少:

private string _password;

我无法想象什么时候我需要能够在内部获取但不设置或设置但不获取私有字段:

private string Password { get; }

or

private string Password { set; }

但也许有嵌套/继承类的用例,或者可能get/set可能包含逻辑,而不仅仅是返回属性的值,尽管我倾向于严格保持属性简单,让显式方法做任何逻辑,例如GetEncodedPassword()。

是否有人出于某种原因在c#中使用私有属性,或者它只是那些技术上可行但在实际代码中很少使用的结构之一?

齿顶高

不错的答案,我仔细阅读了这些私人财产的用途:

当需要惰性加载私有字段时 当私有字段需要额外的逻辑或者是计算值时 因为私有字段很难调试 为了“向自己展示一份合同” 将公开的属性作为序列化的一部分在内部转换/简化 包装要在类中使用的全局变量


当前回答

我使用私有属性来减少访问经常使用的子属性的代码。

    private double MonitorResolution
    {
        get { return this.Computer.Accesories.Monitor.Settings.Resolution; }
    }

如果有很多子属性,它是有用的。

其他回答

如果我需要缓存一个值并想要延迟加载它,我就使用它们。

private string _password;
private string Password
{
    get
    {
        if (_password == null)
        {
            _password = CallExpensiveOperation();
        }

        return _password;
    }
}

我不时地使用它们。当你可以轻松地在属性中添加断点或添加日志记录语句时,它们可以使调试变得更容易。

如果您稍后需要以某种方式更改数据类型或需要使用反射,那么它也很有用。

当存在与属性set或get相关的逻辑时(考虑惰性初始化),并且属性在类中的几个地方使用时,这是非常有意义的。

如果它只是一个直接的后场?我想不出什么好理由。

这是我唯一能想到的用法

private bool IsPasswordSet 
{ 
     get
     {
       return !String.IsNullOrEmpty(_password);
     }
}

属性和字段不是一对一的。属性是关于类的接口(无论是谈论它的公共接口还是内部接口),而字段是关于类的实现。属性不应该被视为仅仅公开字段的一种方式,它们应该被视为公开类的意图和目的的一种方式。

Just like you use properties to present a contract to your consumers on what constitutes your class, you can also present a contract to yourself for very similar reasons. So yes, I do use private properties when it makes sense. Sometimes a private property can hide away implementation details like lazy loading, the fact that a property is really a conglomeration of several fields and aspects, or that a property needs to be virtually instantiated with each call (think DateTime.Now). There are definitely times when it makes sense to enforce this even on yourself in the backend of the class.