查看正在发生的事情(IMO)的最简单方法是将这些属性转换为方法:
// If we didn't have properties, this is what the two first lines would be. Ick!
private int assignedCount;
private int unassignedCount;
public int GetAssignedCount()
{
return assignedCount;
}
public void SetAssignedCount(int value)
{
assignedCount = value;
}
public int GetUnassignedCount()
{
return unassignedCount;
}
public void SetUnassignedCount(int value)
{
unssignedCount = value;
}
// And here's the read-only TotalCount property translation
public int GetTotalCount()
{
return GetUnassignedCount() + GetTotalCount();
}
现在里面的递归GetTotalCount()
应该很清楚了。该方法无条件地调用自身,因此最终会炸毁堆栈。
自动实现的属性的混合以及属性访问看起来像字段访问的事实有时会妨碍记住它们实际上只是伪装的方法。希望上面的翻译能让这一切更加明显。