2 回答

TA貢獻1847條經驗 獲得超11個贊
如果我是你,我會將 Total 計算和 Bust 分開一點:
public class Player
{
public bool Bust { get; set; }
public int GetTotal()
{
if (Bust)
{
return 0;
}
var total = 0;
foreach (int card in hand)
{
total += card;
}
return total;
}
}
需要注意的幾點:
計算是通過一種方法而不是屬性完成的 - 我認為這是一種更簡潔的方法,因為屬性應該非常簡單并且其中沒有任何邏輯
在 GetTotal 計算中包含 Bust 并在 Bust 設置為 true 時返回 0
始終計算總價值,除非您有充分的理由擁有它的緩存版本
希望這可以幫助。

TA貢獻1847條經驗 獲得超7個贊
實際上,每次調用屬性的 getter 時,您都會重新計算總數。
一個解決辦法是讓現場total的Nullable<int>所以如果是null,你做你正在做的其實不然返回的內容在現場設置的邏輯total。
public class Player
{
private int? total; // <- Nullable<int> here
public int Total
{
get
{
if(total.HasValue) // <- If value is set return that value.
{
return total.Value;
}
total = 0;
foreach (int card in hand)
{
total += card;
}
return total.Value;
}
set { this.total = value; }
}
}
- 2 回答
- 0 關注
- 201 瀏覽
添加回答
舉報