下面的两个示例完全相同,在类内部和外部具有相同的访问写入... 那么为什么每个人似乎都使用示例 1 而不是示例 2?我确定我只是错过了一些东西,但这已经困扰了我一段时间,我一直无法找到明确的答案。
class SampleClass
{
/// Example 1
/// Shown by online examples.
/// Why use a Field AND a Property where you could just use Example 2?
private int age;
public int Age { get { return age; } }
private void setAge()
{
age = 1;
}
/// Example 2
/// Tidier code and better understanding of how Age2 can be accessed.
/// Personally I prefer this method, though am I right to use it over Example 1?
public int Age2 { get; private set; }
private void setAge2()
{
Age2 = 1;
}
}