我假設你不想拋出異常,否則你已經這樣做了。就像警告/警告而不停止執行程序。在這種情況下,您仍然可以使用異常,只是不要拋出異常,而是將其作爲輸出參數傳遞,或者放在用戶可以根據需要訪問它的地方。如果這看起來超過了頂部,那麼只需使用一條消息。
將它作爲'嘗試'方法也可能是一個好主意。它清楚地表明該方法在某些條件下容易發生故障。
這些都是不同的選擇:
public bool TryGetBalanceFinale(Periode periode, out List<Balance> list, out string msg)
{
// return false if anything is wrong, and have an out parameter for the result & msg
}
public bool TryGetBalanceFinale(Periode periode, out List<Balance> list, out Exception ex)
{
// return false if anything is wrong, and have an out parameter for the exception
}
上述前兩個是我的兩個首選的方法。以下是可能還有,但它們確實有點不標準:
public Tuple<string, bool> TryGetBalanceFinale(Periode periode, out List<Balance> list)
{
// return false if anything is wrong, and include message in the returned Tuple
}
// an anonymous type approach
public object TryGetBalanceFinale(Periode periode, out List<Balance> list)
{
return new {
Successful = false,
Message = // reason why here
};
}
// a functional approach
public List<Balance> list GetBalanceFinale(Periode periode, Action<String> messageAct)
{
// when something is wrong, do:
messageAct("Something went wrong...");
}
我認爲「嘗試」戰略是很有道理的,當你考慮如何將用於:
string message;
List<Balance> result;
if (!TryGetBalanceFinale(periode, out result, out message))
{
// examine the msg because you know the method failed
Console.WriteLine(message);
}
else
{
// you know the method succeeded, so use the result
Console.WriteLine("The result is: " + result.ToString());
}
儘管我從不特別喜歡'out'參數,但我認爲這個解決方案非常簡潔! – Mathieu
匿名類型的方法讓我感到非常恐怖。我寧願使用實際類型或「元組」。傳遞如何處理錯誤的「行動」的想法有點奇怪,但在某些情況下非常有效。在很多情況下,人們可以比這更進一步,只是將整個事情包裝在一個班級中。如果你這樣做,你會失敗成爲一個事件。 – Brian