财产(没有额外处理)与公共领域

Raj*_*Raj 14 c# properties

每当有关于Properties的可信度的问题时,我发现大多数讨论都是围绕函数/方法和属性进行的.但我也想知道使用属性与相关私有字段直接与公共字段直接使用的令人信服的理由,包含最常见的获取/设置行为而没有其他处理,我的意思是这种方式

public string CustomerName;
Run Code Online (Sandbox Code Playgroud)

VS

private string customerName;
public string CustomerName
{
get{return customerName;}
set(string value){this.customerName=value;}
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 22

如果您以后需要添加其他行为,则可以获得源/二进制兼容性,您可以添加断点,并且它只是在哲学上更清晰(关注行为,而不是存储机制).

请注意,您不需要C#3中的整个后一个块:

public string CustomerName { get; set; }
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅我的文章"为什么属性重要".

  • 如果你的课程中有30个字段,那么你应该使用更多的封装来开始. (7认同)