我可能只是在最接近的使用點捕捉異常。
這是因爲LastOrDefault/FirstOrDefault
超過一個IEnumerable<int>
將返回0(對於int
默認值),其可以是一個「有效」值 - 這取決於實際的上下文和定義的規則。雖然將序列轉換爲IEnumerable<int?>
將允許以前的方法返回null
,這似乎是更多的工作,而不是價值。
如果需要對一個繼續使用使用lastScore
,考慮:
int? lastScore; /* Using a Nullable<int> to be able to detect "not found" */
try {
lastScore = list.Last(x => x < 100); /* int -> int? OK */
} catch (InvalidOperationException) {
lastScore = null; /* If 0 see LastOrDefault as suggested;
otherwise react appropriately with a sentinel/flag/etc */
}
if (lastScore.HasValue) {
/* Found value meeting conditions */
}
或者,如果能夠拋棄時沒有找到的情況下,可以考慮:
try {
var lastScore = list.Last(x => x < 100);
/* Do something small/immediate that won't throw
an InvalidOperationException, or wrap it in it's own catch */
return lastScore * bonus;
} catch (InvalidOperationException) {
/* Do something else entirely, lastScore is never available */
return -1;
}
歡迎SO!說了這些,我很困惑你的問題。 'List'不能是'list'的類型,因爲'int'當然沒有'Score'屬性。請澄清。 –
J0e3gan
2014-09-13 05:07:39
真的很抱歉!我打算寫'list.Last(x => x <100)'。感謝您指出它。我也編輯了這個問題。 – 2014-09-13 05:11:49