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

private string Password { get; set; }

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

private string _password;

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

private string Password { get; }

or

private string Password { set; }

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

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

齿顶高

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

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


当前回答

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

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.

其他回答

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

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

        return _password;
    }
}

我一直在做的一件事是将“全局”变量/缓存存储到HttpContext中。当前的

private static string SomeValue{
  get{
    if(HttpContext.Current.Items["MyClass:SomeValue"]==null){
      HttpContext.Current.Items["MyClass:SomeValue"]="";
    }
    return HttpContext.Current.Items["MyClass:SomeValue"];
  }
  set{
    HttpContext.Current.Items["MyClass:SomeValue"]=value;
  }
}

查看指南(属性(c#编程指南)),似乎没有人期望将属性用作私有成员。

属性使类能够公开获取和设置值的公共方式,同时隐藏实现代码或验证代码。

在任何情况下,它都可以通过一个或两个方法进行交换,反之亦然。

原因可能是在获取时用圆括号,在设置时用字段语法。

这是我唯一能想到的用法

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

另一种用法是在设置值时执行一些额外的操作。

它发生在WPF在我的情况下,当我显示一些信息基于私有对象(不实现INotifyPropertyChanged):

private MyAggregateClass _mac;

private MyAggregateClass Mac
{
    get => _mac;
    set
    {
        if(value == _mac) return;
        _mac = value;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(DisplayInfo)));
    }
}

public string DisplayInfo => _mac.SomeStringInformationToDisplayOnUI;
        

还可以有一些私有方法,例如

private void SetMac(MyAggregateClass newValue)

这样做。