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

private string Password { get; set; }

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

private string _password;

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

private string Password { get; }

or

private string Password { set; }

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

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

齿顶高

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

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


当前回答

我在序列化中使用它们,比如DataContractSerializer或protobuf-net,它们支持这种用法(XmlSerializer不支持)。如果你需要简化一个对象作为序列化的一部分,它是有用的:

public SomeComplexType SomeProp { get;set;}
[DataMember(Order=1)]
private int SomePropProxy {
    get { return SomeProp.ToInt32(); }
    set { SomeProp = SomeComplexType.FromInt32(value); }
}

其他回答

我一直在做的一件事是将“全局”变量/缓存存储到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;
  }
}

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

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 bool IsPasswordSet 
{ 
     get
     {
       return !String.IsNullOrEmpty(_password);
     }
}

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

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

通常只修改使用get/set方法的成员,甚至是私有方法。现在,这背后的逻辑是,所以你知道你的get/set总是以一种特定的方式表现(例如,触发事件),这似乎没有意义,因为这些不会包括在属性方案中……但旧习难改。